如何打印嵌套 map 的内容?我正在计算一个单词在文件中出现的次数,按行号和每行出现的次数来报告。单词、行和每行出现的次数存储在以下容器中:
map<string, map<int, int>> tokens;
但是,我不确定语法。我正在使用以下代码打印列出所有单词的外部 map ,但也不知道如何打印内部值(行号和单词在每行中出现的次数)。我假设我可以将它内联包含在 for
循环中,但我不知道如何:
for (map <string, map<int, int>>::iterator it = tokens.begin(); it != tokens.end(); ++it){
cout << it->first << " : " << /* assume I can include another statement here to print the values? */ endl;
}
我正在尝试获得与此类似的输出:
(单词:行:出现次数,行:出现次数,...)
about : 16:1, 29:1, 166:1, 190:1, 191:1
above : 137:1
accompanied : 6:1
across : 26:1
admit : 20:1
advancing : 170:1
.
.
.
最佳答案
其实很简单
您只需使用它获取内部映射->其次,然后以相同的方式对其进行迭代。
因此,你会写这样的东西:
for (map <string, map<int, int>>::iterator it = tokens.begin(); it != tokens.end(); ++it){
cout << it->first << " : ";
map<int, int> &internal_map = it->second;
for (map<int, int>::iterator it2 = internal_map.begin(); it2 != internal_map.end(); ++it2){
if (it2 != internal_map.begin())
cout << ",";
cout << it2->first << ":" << it2->second;
}
cout << endl;
}
如果你有 C++11 支持,你可以写这样的东西:
for (auto it : tokens) {
cout << it->first << " : ";
map<int, int> &internal_map = it->second;
for (auto it2: internal_map) {
if (it2 != internal_map.begin())
cout << ",";
cout << it2->first << ":" << it2->second;
}
cout << endl;
}
关于c++ - 如何将 map<string, map<int, int>> 的内容打印到 cout 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22889347/