How to Iterate Through Map in C++

Jinku Hu Feb 02, 2024
  1. Use the while Loop With Iterators to Iterate Over std::map Elements
  2. Use Traditional for Loop to Iterate Over std::map Elements
  3. Use Range-Based for Loop to Iterate Over std::map Elements
  4. Use C++17 Structured Binding in Range-Based for Loop to Iterate Over std::map Key-Value Pairs
  5. Use the for_each Algorithm With Lambda Function to Iterate Over std::map Key-Value Pairs
  6. Conclusion
How to Iterate Through Map in C++

The Standard Template Library (STL) in C++ provides a versatile set of containers, and one of the key players in this ensemble is the std::map. Efficiently traversing the elements within a map is a fundamental skill for C++ programmers, and this article will serve as your compass through the various methods available for map iteration.

Use the while Loop With Iterators to Iterate Over std::map Elements

To iterate over the elements of an STL map using a while loop, we employ iterators. An iterator is essentially a pointer-like object that points to an element in the container.

The syntax for a while loop with iterators is as follows:

auto iter = myMap.begin();
while (iter != myMap.end()) {
  // Access key using iter->first
  // Access value using iter->second

  // Increment the iterator
  ++iter;
}

In this syntax:

  • myMap.begin() returns an iterator pointing to the first element of the map.
  • myMap.end() returns an iterator pointing to the position just beyond the last element of the map.
  • The loop continues iterating until the iterator iter reaches the end of the map.

Complete code example:

#include <iostream>
#include <map>

int main() {
  std::map<int, std::string> myMap = {
      {1, "Apple"}, {2, "Banana"}, {3, "Orange"}};

  auto iter = myMap.begin();
  while (iter != myMap.end()) {
    std::cout << "[" << iter->first << "," << iter->second << "]\n";
    ++iter;
  }

  return 0;
}

Output:

[1,Apple]
[2,Banana]
[3,Orange]

In this example, we first include necessary header files, declare a std::map named myMap, and initialize it with a few key-value pairs. Next, we create an iterator iter and set it to the beginning of the map using myMap.begin().

The while loop checks whether the iterator iter has reached the end of the map (myMap.end()). Inside the loop, we use iter->first to access the key and iter->second to access the corresponding value, printing them to the standard output.

Finally, we increment the iterator using ++iter to move to the next element in the map. The loop continues until the iterator reaches the end of the map.

This method provides a clear and efficient way to traverse the elements of an STL map using a while loop with iterators, offering fine-grained control over the iteration process.

Use Traditional for Loop to Iterate Over std::map Elements

Building upon our exploration of STL map iteration, let’s delve into another method of traversing its elements—this time using a for loop with iterators. This approach offers a more concise and expressive syntax, simplifying the code while retaining the efficiency of iterator-based iteration.

for (auto iter = myMap.begin(); iter != myMap.end(); ++iter) {
  // Access key using iter->first
  // Access value using iter->second
}

Here’s a breakdown of the syntax:

  • myMap.begin() returns an iterator pointing to the first element of the map.
  • myMap.end() returns an iterator pointing to the position just beyond the last element of the map.
  • The loop initializes iter at the beginning of the map and continues iterating until it reaches the end, and increments the iterator in each iteration.

Complete working example:

#include <iostream>
#include <map>

int main() {
  std::map<int, std::string> myMap = {
      {1, "Apple"}, {2, "Banana"}, {3, "Orange"}};

  for (auto iter = myMap.begin(); iter != myMap.end(); ++iter) {
    std::cout << "[" << iter->first << "," << iter->second << "]\n";
  }

  return 0;
}

Output:

[1,Apple]
[2,Banana]
[3,Orange]

In this illustrative example, we begin by including the necessary header files and declaring a std::map named myMap. This map is initialized with a few key-value pairs.

Subsequently, we initiate a for loop, creating an iterator iter and setting it to the beginning of the map using myMap.begin(). The loop’s condition (iter != myMap.end()) ensures that we traverse the map until we reach its conclusion.

Within the loop, iter->first grants us access to the key, and iter->second lets us retrieve the associated value. These elements are then printed to the standard output.

As we increment the iterator with ++iter at the end of each iteration, the loop gracefully guides us through the entire map. This method blends clarity with efficiency, making it a compelling choice for looping over STL map elements with a for loop and iterators.

Use Range-Based for Loop to Iterate Over std::map Elements

Now, let’s discuss another method for STL map iteration—the range-based for loop. This modern C++ feature, introduced in C++11, streamlines the process of traversing elements, making the code more readable and concise.

The syntax for a range-based for loop when iterating over the elements of an STL map is remarkably clean:

for (const auto &pair : myMap) {
  // Access key using pair.first
  // Access value using pair.second
}

In this syntax:

  • const auto &pair declares a reference to each key-value pair in the map.
  • : myMap specifies the range, iterating over all elements in the map.

Complete working code example:

#include <iostream>
#include <map>

int main() {
  std::map<int, std::string> myMap = {
      {1, "Apple"}, {2, "Banana"}, {3, "Orange"}};

  for (const auto &pair : myMap) {
    std::cout << "[" << pair.first << "," << pair.second << "]\n";
  }

  return 0;
}

Output:

[1,Apple]
[2,Banana]
[3,Orange]

Now, with the range-based for loop, the map iteration becomes remarkably succinct. The loop header for (const auto &pair : myMap) signifies that for each iteration, a constant reference to each key-value pair in myMap is bound to the variable pair.

Inside the loop, we can effortlessly access the key using pair.first and the corresponding value using pair.second. The loop automatically iterates over all elements in the map, eliminating the need for explicit iterator declarations and manual incrementation.

The range-based for loop not only simplifies the syntax but also enhances code readability. It is particularly advantageous when the intention is to iterate over all elements in a container without the need for explicit control over the iteration process.

This feature is available in C++11 and later versions, making it a powerful tool for modern C++ development.

Use C++17 Structured Binding in Range-Based for Loop to Iterate Over std::map Key-Value Pairs

Another technique we can use for STL map iteration is the combination of structured bindings and the range-based for loop. This approach, introduced in C++17, allows us to directly unpack key-value pairs within the loop header, resulting in more concise and expressive code.

The syntax for utilizing C++17 structured binding in a range-based for loop for iterating over STL map elements is quite simple:

for (const auto &[key, value] : myMap) {
  // Access key using key
  // Access value using value
}

In this syntax:

  • const auto &[key, value] declares references to both the key and value components of each key-value pair.
  • : myMap specifies the range, iterating over all elements in the map.

Complete code example:

#include <iostream>
#include <map>

int main() {
  std::map<int, std::string> myMap = {
      {1, "Apple"}, {2, "Banana"}, {3, "Orange"}};

  for (const auto &[key, value] : myMap) {
    std::cout << "[" << key << "," << value << "]\n";
  }

  return 0;
}

Output:

[1,Apple]
[2,Banana]
[3,Orange]

After including the necessary header files, we declare a std::map named myMap and initialize it with a few key-value pairs. Now, with the C++17 structured binding in a range-based for loop, the iteration becomes even more expressive.

The loop header for (const auto &[key, value] : myMap) signifies that for each iteration, references to both the key and value components of each key-value pair in myMap are directly bound to the variables key and value.

Inside the loop, we can seamlessly access the key using key and the corresponding value using value. The loop automatically iterates over all elements in the map without the need for explicit iterator declarations or manual incrementation.

C++17 structured bindings provide a cleaner and more concise syntax for unpacking elements, enhancing the readability and maintainability of the code. This approach is particularly beneficial when the intention is to work directly with the individual components of each element in the container.

Use the for_each Algorithm With Lambda Function to Iterate Over std::map Key-Value Pairs

Let’s explore another flexible and functional approach—utilizing the for_each algorithm in conjunction with a lambda function. This method provides a concise way to traverse map elements while allowing customization through the lambda function.

The syntax for the for_each algorithm with a lambda function when iterating over the elements of an STL map is both concise and powerful:

#include <algorithm>

std::for_each(myMap.begin(), myMap.end(), [](const auto& pair) {
  // Access key using pair.first
  // Access value using pair.second
});

In this syntax:

  • std::for_each is a standard algorithm that applies a provided function (in this case, a lambda function) to each element in the specified range.
  • myMap.begin() and myMap.end() define the range of elements in the map to be traversed.
  • The lambda function [](const auto& pair) takes each key-value pair as a parameter, allowing access to both the key (pair.first) and value (pair.second).

Complete working example:

#include <algorithm>
#include <iostream>
#include <map>

int main() {
  std::map<int, std::string> myMap = {
      {1, "Apple"}, {2, "Banana"}, {3, "Orange"}};

  std::for_each(myMap.begin(), myMap.end(), [](const auto& pair) {
    std::cout << "[" << pair.first << "," << pair.second << "]\n";
  });

  return 0;
}

Output:

[1,Apple]
[2,Banana]
[3,Orange]

In this example, after including the necessary header files, we declare a std::map named myMap and initialize it with a few key-value pairs. The std::for_each algorithm is then employed to iterate over the map’s elements.

The for_each algorithm is called with the range defined by myMap.begin() and myMap.end(). For each iteration, the provided lambda function is executed.

The lambda function, [](const auto& pair), receives each key-value pair as a parameter. Inside the lambda function, we can access the key using pair.first and the corresponding value using pair.second.

This approach encapsulates the iteration process within the algorithm, providing a clean and functional way to process each element in the map.

Conclusion

Looping over the elements of an STL map in C++ is a fundamental skill when working with associative containers. Whether using iterators or a range-based for loop, understanding these techniques is crucial for efficiently traversing and manipulating the data stored in a map.

As you explore more complex scenarios, mastering these iteration methods will empower you to harness the full potential of C++ and the STL.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C++ Map