Reputation: 113
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.
}
Upvotes: 4
Views: 1379
Reputation: 310950
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
Upvotes: 4
Reputation: 60218
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.
Upvotes: 3