簡體   English   中英

std :: cout地圖<string, int>

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

我有一張地圖聲明如下

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 ,這很可悲...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM