C++ Loop through Map

前端 未结 5 703
抹茶落季
抹茶落季 2020-11-30 16:56

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

What I have so far:



        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 17:47

    You can achieve this like following :

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

    With C++11 ( and onwards ),

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

    With C++17 ( and onwards ),

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

提交回复
热议问题