gpt4 book ai didi

c++ - 遍历 unordered_map C++

转载 作者:可可西里 更新时间:2023-11-01 16:52:12 29 4
gpt4 key购买 nike

我编写了一个程序,它会读取输入,直到您点击“,” - 输入处的 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
cout << " " << it->first << ":" << it->second;


return 0;
}

最佳答案

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

关于c++ - 遍历 unordered_map C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22880431/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com