Search code examples
c++std

Using std::any_of, std::all_of, std::none_of etc with std::map


std::unordered_map<std::string, bool> str_bool_map = {
    {"a", true},
    {"b", false},
    {"c", true}
};

can we use std::any_of on this map to see any of its values is false? Or any of its key is let's say "d"?

Similarly can we use std::all_of or std::none_of on this map?


Solution

  • The simplest solution is to use a lambda:

    std::unordered_map<std::string, bool> str_bool_map = 
        {{"a", true}, {"b", false}, {"c", true}};
    
    bool f = std::any_of(str_bool_map.begin(), str_bool_map.end(),
        [](const auto& p) { return !p.second; });
    

    Here the lambda expression [](...) { ... } is a unary predicate that takes const auto& p and makes the test. const auto& will be deduced to const std::pair<const std::string, bool>& (= std::unordered_map<...>::value_type), that's why you use .second to test the bool part of a pair. Use .first member to test the element's key.