Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

maps

std-pair

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 ?

like image 994
chota bheem Avatar asked Apr 10 '15 11:04

chota bheem


1 Answers

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;
like image 198
Cory Kramer Avatar answered Oct 13 '22 22:10

Cory Kramer