Iterate Through a Map in C++: 4 Best Methods

Imagine you’re managing an online store, handling student grades, or storing country-calling codes. In all these cases, you need a structured way to store and retrieve data efficiently. This is where C++ maps come in! In this article, you’ll explore four unique methods to iterate through a map in C++, each with a real-world example.

What is a Map in C++?

A std::map is a container in C++ that stores key-value pairs in sorted order based on the keys. Each key is unique and has a single associated value. You can think of a map as a real-world dictionary, where a word (key) maps to its definition (value).

Iterate Through a Map in C++ 4 Best Methods

4 Different Ways to Iterate Through a Map in C++

  1. Use iterators for fine control.
  2. Use range-based for loops for readability.
  3. Use while loops for flexibility.
  4. Use lambdas with for_each for modern, concise code.

1. Using an Iterator

Iterators let you access each element in the map one by one. Plus, they provide fine control over the iteration process, so you can move forward, backward or even modify elements as you iterate.

Example Code

  • In this example code, we first create a map called itemsList with integer keys and string values.
  • We then initialize an iterator it with itemsList.begin(), which points to the first element in the map.
  • The condition it != itemsList.end() ensures that the iteration stops when the iterator reaches the end of the map.
  • Inside the loop, it->first accesses the key, and it->second accesses the value of the current map entry, printing the key-value pair on each new line.
#include <iostream>
#include <map>
using namespace std;

int main() {
    // Creating a map
    map<int, string> itemsList = {{2, "Gloves"}, {4, "Tubes"}, {5, "Tapes"}};

   // Using an iterator to iterate through the map
    for (auto it = itemsList.begin(); it != itemsList.end(); ++it) {
        // Accessing and printing the key and value of each element
        cout << "Quantity: " << it->first << ", Item: " << it->second << endl;
    }

    return 0;
}

Output

Quantity: 2, Item: Gloves
Quantity: 4, Item: Tubes
Quantity: 5, Item: Tapes

2. Using a Range-Based for Loop

The range-based for loop is a clean and concise way to iterate through a map, especially when an iterator is not explicitly needed.

Example Code

  • Here, we first create a map named Grades with string keys and string values.
  • We then use a range-based for loop to iterate through the map. The loop for (const auto& pair : Grades) creates a reference pair to each key-value pair in the map.
  • The pair.first and pair.second are used to access the key and the value of each element.
  • Finally, we print the key-value pairs to the output screen.
#include <iostream>
#include <map>
using namespace std;

int main() {
    // Creating a map
    map<string, string> Grades = {{"A", "Charlie"}, {"B", "Zach"}, {"C", "Harry"}};

    // Using a range-based for loop to iterate through the map
    for (const auto& pair : Grades) {
        // Accessing and printing the key and value of each element
        cout << "Grade: " << pair.first << ", Student: " << pair.second << endl;
    }

    return 0;
}

Output

Grade: A, Student: Charlie
Grade: B, Student: Zach
Grade: C, Student: Harry

3. Using a While Loop with an Iterator

You can still iterate through a map if you prefer using a traditional while loop instead of a for loop.

Example Code

  • In this example, we start by creating a map called countryCodes, where the keys are integers and the values are strings.
  • Next, we set up an iterator, it, which points to the first element in the map.
  • Then, we use a while loop to go through each element in the map. The loop keeps running as long as it hasn’t reached the end of the map, which we check using it != countryCodes.end().
  • Inside the loop, we print the key with it->first and the value with it->second.
  • After printing each pair, we move to the next element by incrementing the iterator with ++it. The loop keeps going until we’ve printed all the pairs in the map.
#include <iostream>
#include <map>
using namespace std;

int main() {
    // Creating a map
    map<int, string> countryCodes = {{86, "China"}, {90, "Turkey"}, {92, "Pakistan"}};

    // Initializing an iterator to point to the first element in the map
    auto it = countryCodes.begin();

    // Using a while loop to iterate through the map
    while (it != countryCodes.end()) {
        // Accessing and printing the key and value of each element
        cout << "Country Code: " << it->first << ", Country: " << it->second << endl;
        
        ++it;
    }

    return 0;
}

Output

Country Code: 86, Country: China
Country Code: 90, Country: Turkey
Country Code: 92, Country: Pakistan

4. Using C++ 11 Lambdas with for_each Loop

You can combine C++11 lambdas with for_each loop to iterate through the map. Lambdas allow you to define small, anonymous functions without cluttering your code with extra function calls.

Example Code

  • Here, we also include the algorithm header file along with the standard iostream and map header files to use for_each loop.
  • We use the for_each function, which takes three arguments: the beginning and end of the map (catalogue.begin() and catalogue.end()), and a lambda function that defines what we want to do with each element.
  • The lambda function receives a reference to each pair<int, string> from the map.
  • Inside the lambda, we access the key using element.first and its corresponding value using element.second, and then print both to the screen.
#include <iostream>
#include <map>
#include <algorithm> // Including the algorithm header for for_each
using namespace std;

int main() {
    // Creating a map
    map<int, string> catalogue = {{1001, "Shoes"}, {1002, "Watch"}, {1003, "T-Shirts"}};

    // Using for_each to iterate through the map and apply a lambda function to each element
    for_each(catalogue.begin(), catalogue.end(), [](const pair<int, string>& element) {
        // Inside the lambda function: printing the key and value
        cout << "Product ID: " << element.first << ", Product: " << element.second << endl;
    });

    return 0;
}

Output

Product ID: 1001, Product: Shoes
Product ID: 1002, Product: Watch
Product ID: 1003, Product: T-Shirts

Conclusion

Now that you’ve learned four different ways to iterate through a map in C++, you have a solid foundation for working with maps in your projects.

Remember, C++ maps are useful containers that can greatly improve the performance and organization of your code. So, next time you need to iterate through a map, choose the method that best suits your specific needs.

If you want to learn more about C++ in a simple, easy-to-understand way, check out our C++ series at Syntax Scenarios.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top