【问题标题】:check if map contains a certain value [duplicate]检查地图是否包含某个值[重复]
【发布时间】:2022-01-05 19:42:37
【问题描述】:

您好,我目前遇到一个问题,或者我的想法太复杂了。

我有一张像这样的地图:

  std::map<int,int> mymap;

然后我插入值这样做

 std::map<char,int>::iterator it = mymap.begin();
  mymap.insert (it, std::pair<int,int>(1,300));  

现在我想知道地图是否包含值 300。

假设我有一个名为 input 的变量,其值为 300。

int input = 300;

现在有了这个输入,我想检查我的地图中是否存储了值 300。

我知道使用 map.find() 我可以检查地图中是否存在某个键。 但在我的情况下,我不能使用 map.find(input),因为 300 不是关键,而是价值。

如何检查我的地图中是否有 300 的值?

【问题讨论】:

  • 唯一的办法就是遍历整个地图。
  • @TylerLiu 那么在这种情况下,我的密钥有点不必要,对吗?因为在遍历整个地图时我不需要它
  • 您还可以添加另一个将值映射到键的映射。
  • @konoha 在不了解更多上下文的情况下很难说。仔细检查地图是否真的是您需要的,而不是列表。在这种情况下,密钥的作用是什么?它代表什么?

标签: c++ dictionary stdmap


【解决方案1】:

您可以使用std::find_if 来查找一个值是否存在于std::map 中或下面没有显示:

#include <iostream>
#include <map>
#include <string>
 #include <algorithm>

int main()
{
    // Create a map of three strings (that map to integers)
    std::map<int, int> m { {1, 10}, {2, 15}, {3, 300}, };
    
   int value = 300;
   auto result = std::find_if(std::begin(m), std::end(m), [value](const auto& mo) {return mo.second == value; });
 
   if(result != std::end(m))
   {
       std::cout<<"found"<<std::endl;
   }
    else 
    {
        std::cout<<"not found"<<std::endl;
    }
}

以上程序的输出可见here

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 2011-09-10
    • 1970-01-01
    • 2016-06-27
    • 2014-03-15
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2011-03-27
    相关资源
    最近更新 更多