简体   繁体   中英

Iterate over map with pair as a key

I have a map with pair as a key and third integer as a value. I wonder how to iterate over keys. 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;
}

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;
}

Well, map Key is first item, but itself it is a pair

So

pair<int,int>& key(*it);
cout << key.first << " " << key.second << "\n";

might do the trick

Do you have access to c++11, the auto keyword can make it look a lot nicer. I compiled and ran this fine.

#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(auto it = my_map.begin(); it != my_map.end(); ++it) {
        cout << it->first.first << "\n";
      }

      return 0;
    }
#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.first << "\n";
        cout << it->first.second << "\n";
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM