Is there a way in C++ to search for the mapped value (instead of the key) of a map, and then return the key? Usually, I do someMap.find(someKey)->second
to get the value, but here I want to do the opposite and obtain the key (the values and keys are all unique).
Search by value in a Map in C++ Given a set of N pairs as a (key, value) pairs in a map and an integer K, the task is to find all the keys mapped to the give value K. If there is no key value mapped to K then print “-1”. Explanation: The 3 key value that is mapped to value 3 are 1, 2, 10.
To check if a key exists in a C++ map, you can use std::map::count. It returns 0 (the key is absent) or 1 (the key is present).
map find() function in C++ STL Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map.
C++ Map Library - end() Function The C++ function std::map::end() returns an iterator which points to past-the-end element in the map. The past-the-end element is the theoretical element that would follow the last element in the map.
Because of how a map
is designed, you'll need to do the equivalent of a search on unordered data.
for (auto it = someMap.begin(); it != someMap.end(); ++it) if (it->second == someValue) return it->first;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With