c++ - 如何在 C++ 中检查给定 "KEY"的映射中是否存在 "VALUE"

标签 c++ stl hashmap unordered-map ordered-map

最近我一直在学习 C++ 中的 map ,遇到了各种问题,我需要检查给定值是否存在“KEY”。在 JAVA 中,我们可以通过以下代码片段来做到这一点 -

hash_map.containsValue(VALUE); // Returns true if there is a key for the value, as false

我正在寻找 C++ 中的类似内容。我找到了可以检查“KEY”是否存在的资源,例如:

mp.count(k);  //will return 0 if a key "k" not exists, else it's count

但是如何为“VALUE NOT KEY”做到这一点?

最佳答案

一种简洁的方法是使用 structured binding 循环遍历 map 。 (自 ):

std::map<int, int> map;

for (const auto& [k, v] : map) {
    if (v == VALUE) {
        std::cout << "found value\n";
    }
}

我还建议使用std::find_if并检查返回的找到的迭代器是否有效:

auto it = std::find_if(map.cbegin(), map.cend(), [&](const auto& entry) {
    return entry.second == VALUE;
});

if (it != map.cend()) {
    std::cout << "found value\n";
}

关于c++ - 如何在 C++ 中检查给定 "KEY"的映射中是否存在 "VALUE",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73578616/

相关文章:

c++ - 队列的同步问题

c++ - 在 STL Hash_map 中查找键

c++ - 覆盖映射文件中间数据的有效方法

c++ - 如何从 while 循环中添加数字?

c++ - 围绕世界 0,0,0 而不是对象中心旋转

c++ - float 与定点数 : what are the pros/cons?

java - java如何实现hashmap链碰撞解决

c++ - 带有 std::set 的删除删除习语失败并出现与 constness 相关的错误

c++ - 为什么我们不能像在 C++ 中输入数组那样输入 vector ?

spring-boot - 在 Spring Boot Rest API 中将 Map 用作 @RequestBody 不起作用