在 unordered_map 中查找值

发布于 2024-10-06 10:31:38 字数 114 浏览 0 评论 0原文

我正在使用 Boost unordered_map。我为每个条目都有一个键值对。如何确定地图中是否存在特定值? (我不想创建另一个将值存储为键并将键存储为值的 unordered_map )

谢谢。

I am using Boost unordered_map. I have a key value pair for each entry. How could I determine whether a particular value exist in the map? (I don't want to create another unordered_map which stored the value as key and key as value)

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秋叶绚丽 2024-10-13 10:31:38

怎么样:

typedef std::unordered_map<int,std::string> map_type;
typedef std::unordered_map<int,std::string>::value_type map_value_type;

map_type m;

if (m.end() != find_if(m.begin(),m.end(),[](const map_value_type& vt)
                                           { return vt.second == "abc"; }
                                           ))
   std::cout << "Value found." << std::end;
else
   std::cout << "Value NOT found." << std::end;

或者使用捕获的外部变量:

std::string value = "abc";
if (m.end() != find_if(m.begin(),m.end(),[&value](const map_value_type& vt)
                                                 { return vt.second == value; }))
   std::cout << "Value found." << std::end;
else
   std::cout << "Value NOT found." << std::end;

How about the following:

typedef std::unordered_map<int,std::string> map_type;
typedef std::unordered_map<int,std::string>::value_type map_value_type;

map_type m;

if (m.end() != find_if(m.begin(),m.end(),[](const map_value_type& vt)
                                           { return vt.second == "abc"; }
                                           ))
   std::cout << "Value found." << std::end;
else
   std::cout << "Value NOT found." << std::end;

Or using an external variable that is captured:

std::string value = "abc";
if (m.end() != find_if(m.begin(),m.end(),[&value](const map_value_type& vt)
                                                 { return vt.second == value; }))
   std::cout << "Value found." << std::end;
else
   std::cout << "Value NOT found." << std::end;
那片花海 2024-10-13 10:31:38

Boost 有 Bimap,它是双向映射(即键和值都互相引用)。这听起来比 unordered_map 更适合您的需求。

Boost has the Bimap, which is a bidirectional map (ie, keys and values both refer to each other). This sounds more appropriate for your needs than the unordered_map.

娇纵 2024-10-13 10:31:38

您需要迭代 unordered_map 中的所有元素并查看给定值是否存在。

带有自定义谓词的 std::find_if 算法可用于简化此操作。

You need to iterate over all the elements in the unordered_map and see if the given value exists.

The std::find_if algorithm with a custom predicate can be used to simplify this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文