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

问题描述 投票:1回答:4
std::unordered_map<std::string, bool> str_bool_map = {
    {"a", true},
    {"b", false},
    {"c", true}
};

我们可以在此地图上使用std::any_of来查看其任何值为false吗?还是它的任何键都是"d"

类似地,我们可以在此地图上使用std::all_ofstd::none_of吗?

c++ std
4个回答
4
投票

最简单的解决方案是使用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成员测试元素的键。


4
投票

快速解答:尝试时会发生什么?

另一个快速答案:是

原因:查看this page,我们可以看到std::all_of和朋友期望:

InputIt必须满足LegacyInputIterator的要求。

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

最后,看着std::map.begin(),我们可以看到LegacyBidirectionalIteratorLegacyInputIterator的一种,因此可以将the table herestd::map和朋友一起使用。


1
投票
std::all_of

1
投票

在地图上迭代会产生键值对。因此,您只需将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"; })

© www.soinside.com 2019 - 2024. All rights reserved.