C++ 遍历 Map

2021-12-10 00:00:00 dictionary c++

我想在不知道任何 string-int 值或键的情况下遍历 map 中的每个元素.

I want to iterate through each element in the map<string, int> without knowing any of its string-int values or keys.

到目前为止我所拥有的:

What I have so far:

void output(map<string, int> table)
{
       map<string, int>::iterator it;
       for (it = table.begin(); it != table.end(); it++)
       {
            //How do I access each element?  
       }
}

推荐答案

您可以通过以下方式实现:

You can achieve this like following :

map<string, int>::iterator it;

for (it = symbolTable.begin(); it != symbolTable.end(); it++)
{
    std::cout << it->first    // string (key)
              << ':'
              << it->second   // string's value 
              << std::endl;
}


使用 C++11 (及以后),

for (auto const& x : symbolTable)
{
    std::cout << x.first  // string (key)
              << ':' 
              << x.second // string's value 
              << std::endl;
}


使用 C++17 (及以后),

for (auto const& [key, val] : symbolTable)
{
    std::cout << key        // string (key)
              << ':'  
              << val        // string's value
              << std::endl;
}

相关文章