Home > front end >  Iterate values of a map using range-based for loop
Iterate values of a map using range-based for loop

Time:12-01

Recently I started using range-based for loop. I had a problem where I needed to sort a map by value and then check if value is smaller/larger then some other element/number. Can I do that with this loop?

for (auto& it : M){
    // assign only a value to vector
}

This question would be the same if I had a vector of pairs, could I just check for second, if it is larger then some other element or number? All this using range-based for loop.

CodePudding user response:

From C 20, you can use views::values to get at the values of a std::map, or a vector<pair> for that matter:

for (auto v : m | std::views::values)  // m is some map
  // ...

demo

You can similarly get at the keys with views::keys.

CodePudding user response:

Example using C 20 views to show only those entries in the map of which the value is greater then 2.

#include <iostream>
#include <map>
#include <string>
#include <ranges>

std::map<std::string, int> my_map
{
    {"one", 1},
    {"two", 2},
    {"three", 3},
    {"four", 4}
};

int main()
{

    // create a lambda predicate (a predicate is a function that returns a bool)
    // https://en.cppreference.com/w/cpp/language/lambda
    auto greater_then_2 = [](const auto& pair)
    {
        // use structured binding for readability 
        // (I don't like std::pairs at all for maintainability)
        // https://en.cppreference.com/w/cpp/language/structured_binding
    
        auto [key, value] = pair; // key = pair.first, value = pair.second

        // evaluate predicate
        return value > 2;
    };

    // now loop over all pairs in the map and filter them (C  20 feature)
    // combine structured binding with range based for loops and filters
    for (const auto& [key, value] : my_map | std::views::filter(greater_then_2))
    {
        std::cout << "key = " << key << ", value = " << value << "\n";
    }

    return 0;
}
  •  Tags:  
  • c
  • Related