This post will discuss how to iterate over a map in C++.

The std::begin and std::end function returns an iterator pointing to the first element and the one-past-the-last element in the sequence. We can iterate over a map that starts with std::begin and ends at std::end, as shown below:

Download  Run Code

Output:

{one, 1}
{three, 3}
{two, 2}

 
We can also use the range-based for-loop over the iterator-based for-loop.

Download  Run Code

Output:

{one, 1}
{three, 3}
{two, 2}

 
Starting with C++17, consider using the range-based for-loop with structured bindings:

Download Code

Output:

{one, 1}
{three, 3}
{two, 2}

 
To iterate over the map in reverse order, consider using the range-based for-loop with a reverse adapter offered by the boost library:

Download Code

Output:

{two, 2}
{three, 3}
{one, 1}

 
This is equivalent to the following code using reverse iterators:

Download Code

Output:

{two, 2}
{three, 3}
{one, 1}

That’s all about iterating over a map in C++.