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++.

Download  Run Code

Output:

2
4

 
With C++17 (and onwards), we can use a structured binding inside a range-based for loop:

Download Code

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.

Download Code

Output:

2
4

That’s all about finding all matching keys having a value from a map in C++.