How to Iterate Through a Map in CPP (C++)?

Iterate through Map in Cpp

Do you want to learn more about iterators in CPP (C++) and how to iterate through a map in CPP? 🤔

One of the four elements of the Cpp Standard Template Library, or STL, is iterators. The STL container classes’ memory location is pointed to using an iterator. You could connect them to a pointer to make them easier to understand.

Iterators serve as a link between algorithms and STL containers, enabling the alteration of the data contained inside. To get the desired outcome, you may use them to iterate over the container, read and assign the values, and execute various operators on them.

In this article, we’ll discuss how to iterate through the map in CPP using three different methods. So without further ado, let’s dive deep into the topic and see some real examples. 

 

 

How to Iterate Through a Map in CPP (C++)?

As we’ve discussed in Cpp, we can use the iterator through the map using a Standard Template Library. In Cpp there are three solutions to  Iterate Through a Map in CPP, they are following; 

  1. Using the for loop to Iterate through Map.
  2. Use the while loop to Iterate through Map.
  3. Iterate through a map by using STL Iterator.
  4. Using the foreach loop to Iterate through Map.

 

Method 1: Using the for loop to Iterate through Map

Using the auto keyword in conjunction with the range-based for loop is the easiest method for iterating across a map.

 

Code

#include <iostream>

#include <map>

#include <string>

 

int main()

{

    std::map<std::string, int> map = {

        {"Max", 1}, {"Kelvin", 2}, {"Danial", 3}

    };

 

    for (auto it = map.begin(); it != map.end(); it++) {

        std::cout << "{" << it->first << ", " << it->second << "}" << std::endl;

    }

 

    return 0;

}

 

Output

{Danial, 3}

{Kelvin, 2}

{Max, 1}

 

The iterators returned by the std::begin and std::end functions, respectively, point to the first and one-past-the-last elements in the series. A map that begins with std::begin and ends with std::end can be iterated over, as in the example above.

By using a for loop, you can iterate through a map in C++ and access the elements of the map one by one. This method can be useful if you need to perform a specific action on each element of the map, or if you need to access the elements in a specific order.

 

 

Method 2: Using the while loop to Iterate through Map

To further illustrate possible solutions, we first construct the map structure map and populate it with random key/value pairs, which we will emit to stdout.

 

Code

using std::cout;

using std::cin;

using std::endl;

using std::string;

using std::map;




int main() {

    map<int, string> map = {{1, "Dexton",},

                                {2, "Ben",},

                                {3, "Max",},

                                {4, "Ron",},

                                {5, "Kelvin",},

                                {6, "Daniel",}};




    auto iter = map.begin();

    while (iter != map.end()) {

        cout << "[" << iter->first << ","

                    << iter->second << "]\n";

        ++iter;

    }

    cout << endl;

    return 0;

}

 

Output

[1,Dexton]

[2,Ben]

[3,Max]

[4,Ron]

[5,Kelvin]

[6,Daniel]

 

We have declared the std::map iterator using the auto type specifier as this approach is suggested for readability. It is a mapint, string>::iterator that may be explicitly stated.

 

 

Method 3: Iterating through a map by using STL Iterator

We can successfully iterate over all of the map’s items by establishing an iterator of type std::map, initializing it at the map’s beginning, then visiting it all the way to the end.

Now that we know what to do, let’s look at the example below.

 

Code

#include <iostream>

#include <map>

#include <string>

#include <iterator>

#include <algorithm>




int main()

{

std::map<std::string, int> map;




map.insert(std::pair<std::string, int>("Hanna", 1));

map.insert(std::pair<std::string, int>("Pexton", 2));

map.insert(std::pair<std::string, int>("Kelvin", 3));

map.insert(std::pair<std::string, int>("Parker", 4));

map.insert(std::pair<std::string, int>("Daniel", 5));

map.insert(std::pair<std::string, int>("Mencia", 6));

map.insert(std::pair<std::string, int>("Samuel", 7));




std::map<std::string, int>::iterator it = map.begin();

while (it != map.end())

{

std::string w = it->first;

int count = it->second;

std::cout << w << " :: " << count << std::endl;




it++;

}

return 0;

}

 

Output

Daniel :: 5

Hanna :: 1

Kelvin :: 3

Mencia :: 6

Parker :: 4

Pexton :: 2

Samuel :: 7

 

A map must initially be created before any elements may be added. Once a map iterator that points to the map’s beginning has been established, iterate over the map using the iterator until the map’s end. Then, access the key and value. The iterator then increased the subsequent item’s point.

 

 

Method 4: Using the foreach loop to Iterate through Map

Another way to iterate through a map in C++ is to use the std::for_each function. This function allows you to apply a specific function or lambda expression to each element of the map. Here’s an example:

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

int main()
{
  std::map<int, std::string> myMap;

  // Add some elements to the map
  myMap[1] = "apple";
  myMap[2] = "banana";
  myMap[3] = "cherry";

  // Iterate through the elements of the map and print out the key-value pairs
  std::for_each(myMap.begin(), myMap.end(), [](const std::pair<int, std::string>& pair)
  {
    std::cout << pair.first << ": " << pair.second << std::endl;
  });
}

 

This code will iterate through the elements of the map and print out the key-value pairs. The std::for_each function takes a range of elements (defined by the begin() and end() iterators of the map), and a lambda expression that is applied to each element. The lambda expression takes a pair variable as an argument, and you can access the key and value using the first and second elements of the pair.

By using the std::for_each function, you can easily iterate through a map in C++ and apply a specific function or lambda expression to each element. This can be useful if you need to perform a specific action on each element of the map, or if you want to use a concise and efficient syntax.

 

 

Conclusion

To summarize the article, on how to iterate through a map in c++ we’ve discussed what is an iterator in CPP and how do you iterate through a map in C++? In addition to that, we’ve discussed iterators and how to use them in CPP. There are some methods discussed above to iterate through maps in C++.

As discussed in this article, there could be different methods to iterate through a map in C++ like for loops, while loops, foreach loops, and STL iterators. But the easiest and simplest way to iterate through maps in Cpp is to use the STL iterator. Regardless of which method you choose, you should now have a better understanding of how to iterate through a map in C++.

In conclusion, there are several different ways to iterate through a map in C++, depending on your specific needs and the style of code you prefer. You can use an iterator, a range-based for loop, a for loop, a std::for_each function, or a while loop to access and manipulate the elements of a map.

 Let’s have a quick recap of the topics discussed in this article.

  1. How to Iterate through Map in Cpp?
  2. Use for loop to Iterate through Map.
  3. Use while loop to Iterate through Map
  4. Iterating through a map by using STL Iterator.
  5. Use foreach loop to Iterate through Map.

If you’ve found this article helpful, don’t forget to share and comment below (👇) which solutions have helped you solve the problem.

Total
0
Shares
Leave a Reply

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

Related Posts
Total
0
Share