Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

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?

like image 446
Curious Avatar asked Jan 07 '20 08:01

Curious


1 Answers

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.

like image 84
Evg Avatar answered Dec 09 '22 22:12

Evg