简体   繁体   中英

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

Using the range-v3 library, you can iterate over keys:

for (auto key : m | views::keys)
  // use key

or over values:

for (auto value : m | views::values)
  // use value

where m can be a map .

In c++17, you could do:

for ([[maybe_unused]] auto [key, value] : m)
  // use key or value

Note that the attribute [[maybe_unused]] is used to suppress the warnings about not using one of the variables.

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 

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