The C++ STL (Standard Template Library) includes maps. Maps are associative containers that hold sorted key-value pairs, each of which is identical and can be added or removed but not changed. It is possible to alter the values associated with keys.
Given a map and value, the task is to print all the keys which are having giving value.
Examples:
Example 1:
Input:
map={ { "this", 100 }, { "is", 200 }, { "BTech", 100 }, { "Geeks", 100 } } value =100
Output:
BTech Geeks this
Example 2:
Input:
map={ { "this", 200 }, { "is", 200 }, { "BTech", 100 }, { "Geeks", 100 } } value =200
Output:
this is
Search by value in Map
The objective is to go through the given map and print all of the key values that are mapped to given value. The loop that was used to find all of the key values is shown below.
for(auto &itr : given_Map) { if(itr.second == value) { print(itr.first) } }
If there is no key with the given value then print “Not Found”
Below is the implementation:
#include <bits/stdc++.h> using namespace std; int main() { map<string, int> given_Map; // Givenmap given_Map["this"] = 100; given_Map["is"] = 200; given_Map["BTech"] = 100; given_Map["Geeks"] = 100; // Given value int value = 100; // let us take a boolean value which gives false when // any key is found bool found = true; // Traverse the map for (auto& itr : given_Map) { // if the map value is equal to given value then // print the key // and set boolean value to false if (itr.second == value) { cout << itr.first << " "; found = false; } } // if there are no keys then print not found if (found == true) { cout << "No key found with given value"; } return 0; }
Output:
BTech Geeks this
Related Programs:
- java how to get all keys by a value in hashmap search by value in map
- python how to sort a dictionary by key or value
- python how to find keys by value in dictionary
- python how to get all keys with maximum value in a dictionary
- python how to find an element in tuple by value
- how to copy all values from a map to a vector in cpp
- how to access element by index in a set c