最近我一直在学习 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 。 (自 c++17 ):
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/