Search code examples
c++syntaxiteratorscope-resolution

c++ - iterating through a map of 3 elements


I'm very new to the use of STL containers in C++.

I have a map of 3 elements (2 strings as a pair - acting as the key, and an int acting as the value.)

map<pair<string, string>, int> wordpairs;

But when I try to iterate through it like this:

  for (map<pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.end(); i++) {
      cout << i->first << " " << i->second << "\n";
    }

the compiler is throwing errors:

     error: expected ‘;’ before ‘i’
         for (map<pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.
                                                      ^
    error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
    a7a.cpp:46:50: note: (if you use ‘-fpermissive’ G++ will accept your code)

   error: cannot convert ‘std::map<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, int>::iterator {aka std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, int> >}’ to ‘int’ in assignment
         for (map<pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.
                                                        ^
    error: no match for ‘operator!=’ (operand types are ‘int’ and ‘std::map<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, int>::iterator {aka std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, int> >}’)
         for (map<pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.
                                                                               ^    

    error: expected ‘)’ before ‘;’ token
     pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.end(); i++) {
                                                                                    ^
   error: expected ‘;’ before ‘)’ token
     pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.end(); i++) {

Not sure what I'm doing wrong here - this should be a simple fix though.


Solution

    1. You got the type wrong (you used spaces instead of ::).

    2. Map iterator gives you a key value pair -- and your key is a pair! So you have a pair with a pair as a member. Here's an example that does roughly what you want to do.

      #include <iostream>
      #include <map>
      #include <string>
      #include <utility>
      using namespace std;
      
      int main() {
        pair<string, string> my_key("To", "Be");
        map<pair<string, string>, int> wordpairs { { {"Hello", "World"}, 33} };
        for (const auto& kv : wordpairs) {
          cout << kv.first.first << ", " 
               << kv.first.second << static_cast<char>(kv.second);
        }
        return 0;
      }