简体   繁体   中英

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?

In modern 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:

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:

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

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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