iterating in map/unordered map c++
To iterate over a std::map
or std::unordered_map
container in C++, you can use a range-based for loop or an iterator. Here are explanations for each step:
- Range-based for loop: You can use a range-based for loop to iterate over the elements of a
std::map
orstd::unordered_map
. The syntax for a range-based for loop is as follows:
cpp
for (const auto& pair : map) {
// code to be executed for each element
}
In this loop, pair
represents each element of the map. The const auto&
is used to automatically deduce the type of the element and bind it to a reference, ensuring that the loop operates efficiently. You can choose a different name instead of pair
if you prefer.
- Iterator: Alternatively, you can use an iterator to iterate over the elements of a
std::map
orstd::unordered_map
. Here is an example of how to do that:
cpp
for (auto it = map.begin(); it != map.end(); ++it) {
// code to be executed for each element
}
In this loop, it
is an iterator that starts at the beginning of the map (map.begin()
) and iterates until the end of the map (map.end()
). The ++it
statement increments the iterator to move to the next element in the map.
Inside the loop, you can access the key and value of each element using the first
and second
member variables of the iterator. For example, it->first
represents the key, and it->second
represents the value.
Note: If you want read-only access to the elements, you can use const auto& it
instead of auto it
in the iterator declaration.
That's it! You can choose either the range-based for loop or the iterator approach to iterate over a std::map
or std::unordered_map
in C++. Let me know if you need further assistance!