将 std::any_of、std::all_of、std::none_of 等与 std::map 一起使用

Cur*_*ous 6 c++ std

std::unordered_map<std::string, bool> str_bool_map = {
    {"a", true},
    {"b", false},
    {"c", true}
};
Run Code Online (Sandbox Code Playgroud)

我们可以std::any_of在这张地图上使用它来查看它的任何值false吗?或者它的任何一个关键是让我们说"d"

同样,我们可以在这张地图上使用std::all_ofstd::none_of吗?

Evg*_*Evg 10

最简单的解决方案是使用 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; });
Run Code Online (Sandbox Code Playgroud)

这里的 lambda 表达式[](...) { ... }是一个接受const auto& p并进行测试的一元谓词。const auto&将被推导出const std::pair<const std::string, bool>&(= std::unordered_map<...>::value_type),这就是为什么你.second用来测试对的bool一部分。使用.firstmember 来测试元素的键。


Ken*_*Y-N 5

快速回答:当你尝试时会发生什么?

另一个快速回答:是的

原因:看这个页面我们可以看到,std::all_of朋友们期望:

InputIt必须满足的要求LegacyInputIterator

现在,std::map.begin()返回一个LegacyBidirectionalIterator

最后,查看这里的表格,我们可以看到LegacyBidirectionalIterator是一种LegacyInputIterator,因此您可以使用std::mapwithstd::all_of和朋友。