c ++ - 迭代3个元素的映射

时间:2016-11-06 04:02:32

标签: c++ syntax iterator scope-resolution

我对在C ++中使用STL容器非常陌生。

我有一个包含3个元素的地图(两个字符串作为一对 - 充当键,一个int作为值。)

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

但是当我尝试像这样迭代它时:

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

编译器抛出错误:

     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++) {

不确定我在这里做错了什么 - 这应该是一个简单的修复。

2 个答案:

答案 0 :(得分:3)

  1. 您的类型错误(您使用的是空格而不是::)。

  2. Map iterator为您提供一个键值对 - 您的键是一对!所以你有一对作为成员。这是一个大致完成你想做的事情的例子。

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

答案 1 :(得分:2)

你忘记了::在迭代器之前 您还可以使用auto关键字:

for (auto i = wordpairs.begin(); i != wordpairs.end(); ++i) {
  cout << i->first << " " << i->second << "\n";
}

或仅使用基于范围的for循环:

for (auto& i : wordpairs) {
  cout << i->first << " " << i->second << "\n";
}