C++中如何判断一个值是否存在于map中

How to determine whether a value exists in map in C++

我知道 std::map 是 (Key, Value) 对。

我想搜索地图的值。假设我想在 std::map 中的值中找到最高值。我怎样才能做到这一点 ? 例如让我考虑这样的地图:

John -> 100

Jeffrey -> 200

Krishna -> 147

我想它会和这个类似,但我不确定。

 for (auto it=m.begin(); it!=m.end(); it++)
    { 
       if (it->second == 500)
          { 
             cout << "Found"; 
          }
        else { 
             continue;}
   }

不是遍历[=​​24=],是否有任何其他内置方法可以使用它来检查std::map中是否存在一个值O( 1)时间复杂度?

第二个问题,使用:

std::map<std::string, int> foo = {{"John",100},{"Jeffrey",200},{"Krishna",147}};
std::cout << std::max_element(foo.begin(), foo.end(), [](const auto& p1, const auto& p2){return p1.second < p2.second;})->first;
std::cout << std::min_element(foo.begin(), foo.end(), [](const auto& p1, const auto& p2){return p1.second < p2.second;})->first;

将经过改编的 lambda 与 std::find_if 结合使用,您应该还可以找到某个值是否存在于映射(或散列 table)中。

Q1: How to check if a value exists in hashmap?

您需要遍历并检查是否存在此类项目。您可以将 `std::find_if() 与 lambda 一起使用或通过循环执行此操作。如果你经常这样做,你可能还想索引值(见下文)

Q2: How to iterate through all the values in a map and find the largest value or the smallest value ?

再次遍历容器并找到它,或者您可以使用 std::max_element() or std::min_element() with a lambda as well. Though if you need to access values in sorted order you may consider to use boost::multimap,这将允许按名称使用散列索引访问数据,并为值提供排序或散列索引,但您应该知道添加的每个指数的价格。