简体   繁体   English

std :: cout地图<string, int>

[英]std::cout for map<string, int>

I have a map declared as follows 我有一张地图声明如下

map<string, int> symbolTable;


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

How do I std::cout all of the things in my symbol table? 我如何std :: cout我的符号表中的所有内容?

In modern C++: 在现代C ++中:

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

If you only have access to a pre-C++11 compiler the code would be: 如果您只能访问C ++ 11之前的编译器,则代码为:

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

Here's an alternative if your compiler isn't C++11 compliant: 如果您的编译器不符合C ++ 11,这是一种替代方法:

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

And for completeness, if it is: 为了完整性,如果是这样的话:

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

You can use a loop to print all the key/value pairs. 您可以使用循环来打印所有键/值对。 The code following is an example in C++11 以下代码是C ++ 11中的示例

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

ps: Both of other two answers pay little attention to const , which is quite sad... ps:另外两个答案都很少注意const ,这很可悲...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM