Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over a map with a pair as key?

I have a map with a pair<int, int> as key and a third integer as value. How can I iterate over the map's keys in order to print them? My example code is pasted below:

#include <iostream>
#include <map>
#include <algorithm>

using namespace std;

int main ()
{
  map <pair<int, int>, int> my_map;
  pair <int, int> my_pair;

  my_pair = make_pair(1, 2);
  my_map[my_pair] = 3;

  // My attempt on iteration
  for(map<pair<int,int>,int>::iterator it = my_map.begin(); it != my_map.end(); ++it) {
    cout << it->first << "\n";
  }

  return 0;
}

How do I have to modify the cout line, so that it works?

like image 530
Andrej Avatar asked Dec 14 '22 18:12

Andrej


1 Answers

it->first is an object of type const std::pair<int, int> that is it is the key. it->second is an object of type int that is it is the mapped value. If you want simply to output the key and the mapped value you could write

for ( map<pair<int,int>,int>::iterator it = my_map.begin(); it != my_map.end(); ++it ) 
{
    cout << "( " << it->first.first << ", " 
                 << it->first.second 
                 << " ): "
                 << it->second
                 << std::endl;
}

Or you could use the range-based for statement

for ( const auto &p : my_map )
{
    cout << "( " << p.first.first << ", " 
                 << p.first.second 
                 << " ): "
                 << p.second
                 << std::endl;
}
like image 135
Vlad from Moscow Avatar answered Jan 05 '23 13:01

Vlad from Moscow