迭代无序的地图C++

Yod*_*oda 8 c++ iterator unordered-map

我写了一个程序,它读取输入,直到你点击',' - 输入的COMA.然后它计算你输入的字母数,

我想迭代这个地图,但它说it无法定义,没有类型:

#include <iostream>
#include <conio.h>
#include <ctype.h>

#include <iostream>
#include <string>
#include <tr1/unordered_map>
using namespace std;

int main(){
    cout<<"Type '.' when finished typing keys: "<<endl;
    char ch;
    int n = 128;
    std::tr1::unordered_map <char, int> map;


    do{
      ch = _getch();
    cout<<ch;
      if(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'){
            map[ch] = map[ch] + 1;
      }
    } while( ch != '.' );

    cout<<endl;

    for ( auto it = map.begin(); it != map.end(); ++it ) //ERROR HERE
        std::cout << " " << it->first << ":" << it->second;


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bas*_*tch 23

你正在使用auto所以你有C++ 11代码.您需要符合C++ 11的编译器(例如GCC 4.8.2或更高版本).正如彼得G.所评论的那样,不要将你的变量命名为map(std::map但是),例如mymap 那么请

#include <unordered_map>
Run Code Online (Sandbox Code Playgroud)

(不需要tr1!)

然后编译g++ -std=c++11 -Wall -g yoursource.cc -o yourprog并编写基于for循环范围

for (auto it : mymap) 
    std::cout << " " << it.first << ":" << it.second << std::endl;
Run Code Online (Sandbox Code Playgroud)

  • 它是`it.first`和`it.second`,因为迭代器会自动解除引用 (7认同)
  • 如果您不想复制值,请使用`auto&it`. (6认同)

小智 19

使用C++ 17,您可以使用更短,更智能的版本,如下面的代码所示:

unordered_map<string, string> map;
map["hello"] = "world";
map["black"] = "mesa";
map["umbrella"] = "corporation";
for (const auto & [ key, value ] : map) {
    cout << key << ": " << value << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不进行统一的初始化和推论:http://coliru.stacked-crooked.com/a/876ab2ba7e8473b1 (2认同)