是否有一种通过键和值搜索的好方法?

时间:2010-10-03 03:41:51

标签: c++ stl

我目前在C ++中使用map<int, int>。我可以检查密钥的存在而没有问题但是有一种有效的方法来检索特定值具有的密钥吗?我的目的是获取具有给定值的所有元素,然后更新它们的值。

2 个答案:

答案 0 :(得分:8)

您可能对Boost.Bimap感兴趣。

答案 1 :(得分:0)

现在使用c ++ 11及更高版本很容易。

请尝试以下示例。

//DECLARE A MAP
std::map<int, int> testmap;

//SAMPLE DATA
testmap.insert(std::make_pair(1, 10));
testmap.insert(std::make_pair(2, 20));
testmap.insert(std::make_pair(3, 30));
testmap.insert(std::make_pair(4, 20));

//ELEMENTS WITH VALUE TO BE FOUND
int value = 20;

//RESULTS
std::map<int,int> keysMatching;

//ONE STEP TO FIND ALL MATCHING MAP ELEMENTS
std::copy_if(testmap.begin(), testmap.end(), std::inserter(keysMatching, keysMatching.end()), [value](const auto& v) {return v.second == value; });
相关问题