Map Value Search
Part of the Logic & Flow section of Coddy's C++ journey — lesson 55 of 56.
Challenge
EasyCreate 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
nrepresenting the number of key-value pairs to add to the map - Then
npairs of inputs, each consisting of:- A string
keyrepresenting the key - An integer
valuerepresenting the value
- A string
- An integer
targetValuerepresenting the value to search for
Your program should:
- Create a function named
findKeysWithValuethat takes astd::map<std::string, int>and an integer as parameters - The function should return a
std::vector<std::string>containing all keys that have the specified value - In the main function, create a map and populate it with the input key-value pairs
- Call the
findKeysWithValuefunction with the map and target value - 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: 0Remember 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
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items