迭代3个元素的映射

iterating through a map of 3 elements

本文关键字:映射 元素 3个 迭代      更新时间:2023-10-16

我对c++中STL容器的使用非常陌生。

我有一个3个元素的映射(2个字符串作为一对-作为键,和一个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++) {

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

  1. 您输入错误(您使用空格而不是::)。

  2. Map迭代器给你一个键值对——你的键就是一对!所以你有一对和另一对作为成员。下面的例子大致可以满足您的要求。

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

你忘了::before iterator.
你也可以使用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";
}