C++ 在 std::map 中搜索特定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4367892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search for specific value in std::map
提问by B?ови?
Possible Duplicates:
Checking value exist in a std::map - C++
How to traverse a stl map/vector/list/etc?
Hello,
你好,
Is it possible to search for specific value in std::map, not knowing the key? I know I could iterate over whole map, and compare values, but it is possible to do using a function from std algorithms?
是否可以在不知道键的情况下在 std::map 中搜索特定值?我知道我可以遍历整个地图并比较值,但是可以使用 std 算法中的函数吗?
采纳答案by Platinum Azure
Will this help? STL find_if
这会有所帮助吗?STL find_if
You need to have some sort of predicate, either a function pointer or an object with operator()
implemented. Said predicate should take just one parameter.
您需要有某种谓词,函数指针或已operator()
实现的对象。所述谓词应仅采用一个参数。
回答by icecrime
Well, you could use std::find_if
:
好吧,你可以使用std::find_if
:
int main()
{
typedef std::map<int, std::string> my_map;
my_map m;
m.insert(std::make_pair(0, "zero"));
m.insert(std::make_pair(1, "one"));
m.insert(std::make_pair(2, "two"));
const std::string s("one");
const my_map::const_iterator it = std::find_if(
m.begin(), m.end(), boost::bind(&my_map::value_type::second, _1) == s
);
}
But that's just slightly better than a hand-crafted loop : it's still O(n)
.
但这只是比手工制作的循环稍微好一点:它仍然是O(n)
.
回答by Steve Townsend
You could use Boost.Bimapif you want to index on values as well as keys. Without this or similar, this will have to be done by brute force (=> scan the map
by hand).
如果您想对值和键进行索引,则可以使用Boost.Bimap。如果没有这个或类似的,这将不得不通过蛮力来完成(=>map
手动扫描)。
Boost.Bimap is a bidirectional maps library for C++. With Boost.Bimap you can create associative containers in which both types can be used as key.
Boost.Bimap 是 C++ 的双向映射库。使用 Boost.Bimap 您可以创建关联容器,其中两种类型都可以用作键。
回答by Marcelo Cantos
There are (awkward) ways to do this using standard functions (e.g., std::find_if
), but these still involve iterating over the whole map. Boost.Bimapwill provide efficient indexing in both directions, and you can go even further with Boost.Multi-Index.
有(笨拙的)方法可以使用标准函数(例如 )来做到这一点std::find_if
,但这些方法仍然涉及对整个地图进行迭代。Boost.Bimap将在两个方向上提供高效的索引,您可以使用Boost.Multi-Index走得更远。