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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With