Find all matching keys having a value from a std::map in C++
This post will discuss how to find all matching keys having a value from a map in C++.
1. Using Loop
A simple solution is to use an iterator-based for-loop to iterate over all mapping in the map, and filter values that match with the specified target. This can be implemented as follows in C++.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <string> #include <map> #include <vector> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'B'} }; char target = 'B'; std::vector<int> keys; for (auto it = map.begin(); it != map.end(); it++) { if (it->second == target) { keys.push_back(it->first); } } for (const auto &key: keys) { std::cout << key << std::endl; } return 0; } |
Output:
2
4
With C++17 (and onwards), we can use a structured binding inside a range-based for loop:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <algorithm> #include <map> #include <vector> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'B'} }; char target = 'B'; std::vector<int> keys; for (auto const &[key, val] : map) { if (val == target) { keys.push_back(key); } } for (const auto &key: keys) { std::cout << key << std::endl; } return 0; } |
Output:
2
4
2. Using BOOST_FOREACH
The BOOST_FOREACH simplifies C++ loops by avoiding dealing with iterators or predicates directly. For example, the following program uses BOOST_FOREACH to loop over the contents of a map, and retrieve all keys that match a given value.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> #include <string> #include <map> #include <vector> #include <boost/foreach.hpp> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'B'} }; char target = 'B'; std::vector<int> keys; std::pair<int, char> entry; BOOST_FOREACH(entry, map) { if (entry.second == target) { keys.push_back(entry.first); } } for (const auto &key: keys) { std::cout << key << std::endl; } return 0; } |
Output:
2
4
That’s all about finding all matching keys having a value from a map in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)