c++ - 如何将 map<string, map<int, int>> 的内容打印到 cout 中?

标签 c++ string dictionary iterator output

如何打印嵌套 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/

相关文章:

c++ - 更改 QGraphicsScene/Qt5 中的 Pixmap 位置

java - 修复字符串中格式错误的省略号

python - 在python中打开一个新的行分隔文本文件

java - 字节数组到字符串并反转 : recoverded byte array is NOT match to original byte array in Java

python - 如何使用顺序键将 Numpy 数组转换为 Python 字典?

dictionary - 检查sortedMap中的重复值

c++ - boost::geometry::distance 使用 3D 基元编译错误

c++ - 从 unsigned const char * 类型转换为 char const *

ios - 获取简短的 Google map URL 以在 iOS 中共享

c++ - 死代码识别 (C++)