Menu
Coddy logo textTech

Map Value Search

Part of the Logic & Flow section of Coddy's C++ journey — lesson 55 of 56.

challenge icon

Challenge

Easy

Create a program that implements a reverse lookup system for finding all keys associated with a specific value in a map. This challenge will test your ability to combine map iteration, value comparison, and vector building to search through key-value pairs efficiently.

The following inputs will be provided:

  • An integer n representing the number of key-value pairs to add to the map
  • Then n pairs of inputs, each consisting of:
    • A string key representing the key
    • An integer value representing the value
  • An integer targetValue representing the value to search for

Your program should:

  1. Create a function named findKeysWithValue that takes a std::map<std::string, int> and an integer as parameters
  2. The function should return a std::vector<std::string> containing all keys that have the specified value
  3. In the main function, create a map and populate it with the input key-value pairs
  4. Call the findKeysWithValue function with the map and target value
  5. Print the count of matching keys first, then print each matching key on a separate line

Use the following exact output format:

First line - count of matching keys:

Keys found: [number_of_matching_keys]

Then each matching key on separate lines:

[matching_key_1]
[matching_key_2]
...

If no keys have the target value, only print:

Keys found: 0

Remember that your findKeysWithValue function should create a new empty vector, iterate through the map using a range-based for loop, and use an if-statement to check each pair's value against the target. When a match is found, add the key (accessed via pair.first) to the result vector using push_back(). The function should return the vector containing all matching keys.

Try it yourself

#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;

// TODO: Write your findKeysWithValue function here

int main() {
    // Read number of key-value pairs
    int n;
    cin >> n;
    
    // Create map to store key-value pairs
    map<string, int> keyValueMap;
    
    // Read n key-value pairs
    for (int i = 0; i < n; i++) {
        string key;
        int value;
        cin >> key >> value;
        keyValueMap[key] = value;
    }
    
    // Read target value to search for
    int targetValue;
    cin >> targetValue;
    
    // TODO: Call your findKeysWithValue function and store the result
    
    // TODO: Print the results in the required format
    // First print "Keys found: [count]"
    // Then print each matching key on separate lines
    
    return 0;
}

All lessons in Logic & Flow