Open In App

Search by value in a Map in C++

Improve
Improve
Like Article
Like
Save
Share
Report

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 given value K. If there is no key value mapped to K then print “-1”.
Examples: 

Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 3 
Output: 1 2 10 
Explanation: 
The 3 key value that is mapped to value 3 are 1, 2, 10.
Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 10 
Output: -1 
Explanation: 
There is no any key value that is mapped to value 10. 

Approach: The idea is to traverse the given map and print all the key value which are mapped to the given value K. Below is the loop used to find all the key value: 

for(auto &it : Map) { 
if(it.second == K) { 
print(it.first) 


 

If there is no value mapped with K then print “-1”.
Below is the implementation of the above approach:

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


Output: 

1 2 10

 

Time Complexity: O(N), where N is the number of pairs stored in map. This is because we are traversing all the pairs once.
Auxiliary Space: O(N)



Last Updated : 24 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads