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)
小智 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)