c++ - How to get first and second element of pair if used as key in map?

chota bheem picture chota bheem · Apr 10, 2015 · Viewed 41.1k times · Source

I was trying to get first and second element of pair when i am using pair as key in map.For better clarification please see code below.This is what i have tried

#include <bits/stdc++.h>
using namespace std;

int main() 
{
// your code goes here
map<pair<int,int>,int>mp;
int n;
cin>>n;
int a[n];
for(int i=0;i<n;++i)cin>>a[i];
int y=0;
for(int i=0;i<n;++i)
{
    mp.insert(make_pair(y,a[i]));
    y=a[i]+1;
}
int m;
cin>>m;
int q[m];
for(int i=0;i<m;++i)cin>>q[i];
for(int i=0;i<m;i++)
{
    int temp=q[i];
    for(map<pair<int,int>,int>::iterator it=mp.begin();it!=mp.end();++it)
    {
        if(((it->first)<=temp)&&((it->second)>=temp))
        cout<<mp->second<<endl;
    }

  }
  return 0;
}

I want to get first and second element of key here.How can i do that ?

Answer

Cory Kramer picture Cory Kramer · Apr 10, 2015

When you iterate over your map, you can get the following items

std::pair<int, int> key = it->first;
int value = it->second;

Therefore the first and second value of the key would be

it->first.first;
it->first.second;