search by value in map in stl/cpp
// C++ program for the above approach #include "bits/stdc++.h" using namespace std; // Function to find the key values // according to given mapped value K void printKey(map<int, int>& Map, int K) { // If a is true, then we have // not key-value mapped to K bool a = true; // Traverse the map for (auto& it : Map) { // If mapped value is K, // then print the key value if (it.second == K) { cout << it.first << ' '; a = false; } } // If there is not key mapped with K, // then print -1 if (a) { cout << "-1"; } } // Driver Code int main() { map<int, int> Map; // Given map Map[1] = 3; Map[2] = 3; Map[4] = -1; Map[7] = 2; Map[10] = 3; // Given value K int K = 3; // Function call printKey(Map, K); return 0; }
Source: www.geeksforgeeks.org