Legend
Legend

Reputation: 116810

Is there a good way to search by both key and value?

I am currently using map<int, int> in C++. I can check for the existence of a key without a problem but is there an efficient way to retrieve the keys that a particular value has as well? My purpose is to grab all the elements with a given value and then update their value.

Upvotes: 4

Views: 2068

Answers (2)

Pavan Chandaka
Pavan Chandaka

Reputation: 12751

Now it is easy with c++11 and above.

Try below sample.

//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; });

Upvotes: 0

Fred Larson
Fred Larson

Reputation: 62063

You might be interested in Boost.Bimap.

Upvotes: 9

Related Questions