std::unordered_map<std::string, bool> str_bool_map = {
{"a", true},
{"b", false},
{"c", true}
};
我们可以在此地图上使用std::any_of
来查看其任何值为false
吗?还是它的任何键都是"d"
?
类似地,我们可以在此地图上使用std::all_of
或std::none_of
吗?
最简单的解决方案是使用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; });
这里,lambda表达式[](...) { ... }
是采用const auto& p
并进行测试的一元谓词。 const auto&
将推导为const std::pair<const std::string, bool>&
(= std::unordered_map<...>::value_type
),这就是为什么要使用.second
测试一对中的bool
部分的原因。使用.first
成员测试元素的键。
快速解答:尝试时会发生什么?
另一个快速答案:是
原因:查看this page,我们可以看到std::all_of
和朋友期望:
InputIt必须满足LegacyInputIterator的要求。
现在,std::map.begin()
returns一个LegacyBidirectionalIterator
最后,看着std::map.begin()
,我们可以看到LegacyBidirectionalIterator是LegacyInputIterator的一种,因此可以将the table here与std::map
和朋友一起使用。
std::all_of
在地图上迭代会产生键值对。因此,您只需将lambda传递给算法即可解包键值对。
要检查值,请使用#include <algorithm>
#include <map>
int main()
{
std::map<std::string, bool> map;
map["foo"] = false;
map["bar"] = true;
map["baz"] = false;
const bool any = std::any_of(map.begin(), map.end(), [](const auto& pair)
{
return !pair.second;
});
const bool all = std::all_of(map.begin(), map.end(), [](const auto& pair)
{
return !pair.second;
});
const bool none_of = std::none_of(map.begin(), map.end(), [](const auto& pair)
{
return !pair.second;
});
}
:
.second
要检查键,请使用std::any_of(m.begin(), m.end(), [](const auto& kvp){ return kvp.second; });
:
.first
实时代码std::any_of(m.begin(), m.end(), [](const auto& kvp){ return kvp.first == "d"; })
。