This post will discuss how to retrieve all keys from a map in C++.

1. Using Loop

We can write custom logic for retrieving all keys from the map. The idea is to iterate over the map using a range-based for loop or iterator-based for-loop and insert each key into a container.

Download  Run Code

Output:

1
2
3
4

 
Starting with C++17, we can use the range-based for-loop with structured bindings:

Download Code

Output:

1
2
3
4

2. Using BOOST_FOREACH

The BOOST_FOREACH simplifies loops in C++ by avoiding dealing with iterators or predicates directly. The following program iterates over the contents of a map using BOOST_FOREACH and fetches all keys.

Download Code

Output:

1
2
3
4

 
Alternatively, we can use the range adaptor provided by the boost library. Here’s an example of its usage:

Download Code

Output:

1
2
3
4

3. Using std::transform

Another alternative is to use the std::transform algorithm to convert the map to a vector of keys. It applies an operation to the specified range and stores the result in another range.

Download  Run Code

Output:

1
2
3
4

 
Starting with C++14, we can replace decltype()::value_type with auto.

Download  Run Code

Output:

1
2
3
4

4. Using ranges library

With C++20, the standard library introduced the ranges library. It comes with view adaptors that are lazy views over containers and their transformations. To get a keys view of a map using ranges library, do like:

Download Code

Output:

1
2
3
4

That’s all about retrieving all keys from a map in C++.