Reputation: 116810
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
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