C ++在地图中按值查找 [英] c++ find by value in map

查看:30
本文介绍了C ++在地图中按值查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在地图中按值找到对应的键.
我可以线性地迭代并找到密钥,但是如果我的所有值也都是唯一的,我们还有另一个更好的解决方案吗?

I wanted to find in map by value corresponding key.
I can iterate linearly and find the key, but do we have another better solution if my all values are also unique.

提前谢谢.

推荐答案

您可以使用 std :: find_if

#include <algorithm>

template<typename M, typename V>
auto get_map_iterator_from_value(const M& m, const V& v) {
    return std::find_if(std::begin(m), std::end(m),
                        [&v](const auto& pair) { return pair.second == v; });
}

...

auto it = get_map_iterator_from_value(your_map, your_value);

,但是它比在 key 上查询时要慢,因为它也必须遍历地图中的每个条目,直到找到匹配项.

but it'll be slower than when querying on key since it too will have to go through every entry in the map until it finds a match.

与顺序搜索相比,在搜索包含多个条目的映射时的一项改进可能是利用 std :: find_if 的并行执行支持:

An improvement, compared to sequenced searching, when searching a map with many entries could be to make use of std::find_ifs parallel execution support:

#include <algorithm>
#include <execution>

template<typename M, typename V>
auto get_map_iterator_from_value(const M& m, const V& v) {
    return std::find_if(std::execution::par, std::begin(m), std::end(m),
                        [&v](const auto& pair) { return pair.second == v; });
}

如果这真的使它更快或更不需要使用实际地图进行测试.

If that really makes it faster or not has to be tested with your actual map.

注意:如果您经常需要这样做,则可以使用双向地图,例如 Boost.Bimap 更好.

Note: If you need to do this often a bidirectional map like Boost.Bimap is better.

这篇关于C ++在地图中按值查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆