Search code examples
c++loopsfor-loopunordered-mapvalue-type

Access only one element of a pair in an unordered_map in c++


I'm trying to get the same behavior as a rust tuple destructuring in C++. For example: I have an unordered_map I want to iterate over. However, The only data that I care about are the values, and not keys.

Is there a way to iterate over it with a for loop without using the following syntax ? (which is what I have for now)

for (auto &pair : _map)
{
   std::cout << pair.second << std::endl;
}

I would want to get something like this:

for (auto &value : _map)
{
   std::cout << value << std::endl; // This would give me the value and not a pair with key and value.
}

Solution

  • If your compiler supports the C++ 17 Standard then you can write something like the following

    #include <iostream>
    #include <unordered_map>
    #include <string>
    
    int main() 
    {
        std::unordered_map<int, std::string> m =
        {
            { 1, "first" },
            { 2, "second" }
        };
    
        for ( const auto &[key, value] : m )
        {        
            std::cout << value << ' ';
        }
        std::cout << '\n';
    
        return 0;
    }
    

    The program output is

    second first