std::cout for map<string, int>

std::cout for map<string, int>

本文关键字:string int gt lt for map std cout      更新时间:2023-10-16

我有一个如下声明的map

map<string, int> symbolTable;

if(tempLine.substr(0,1) == "("){
            symbolTable.insert(pair<string, int>(tempLine, lineCount));
        }

我如何std::cout所有的东西在我的符号表?

现代c++:

for (auto&& item : symbolTable)
    cout << item.first << ": " << item.second << 'n';

如果你只能使用c++ 11之前的编译器,代码将是:

for ( map<string, int>::const_iterator it = symbolTable.begin(); it != symbolTable.end(); ++it)
    cout << it->first << ": " << it->second << 'n';

如果你的编译器不兼容c++ 11,这里有一个选择:

for (map<string, int>::iterator it = symbolTable.begin();
    it != symbolTable.end(); ++it)
{
    cout << it->first << " " << it->second << endl;
}

为完整起见,如果是:

for (auto& s : symbolTable)
{
    cout << s.first << " " << s.second << endl;
} 

可以使用循环来打印所有的键/值对。下面的代码是c++ 11

中的示例
for (const auto& kv : symbolTable) {
    std::cout << kv.first << " " << kv.second << 'n';
}

ps:其他两个答案都很少关注const,这是相当可悲的…