In C++,std::map
It is an associated container that stores key-value pairs and sorts the keys in the order of the keys. Traversalstd::map
There are many ways, and the following are several common ways:
1. Use range for loop (C++11 and above)
Range-based for loop is a simple way to traverse containers introduced by C++11.
#include <iostream> #include <map> int main() { std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}}; for (const auto& pair : myMap) { std::cout << "Key: " << << ", Value: " << << std::endl; } return 0; }
In this example,pair
is a key and valuestd::pair
Object,It's the key,
is value.
2. Use the iterator
Iterators are the traditional way to traverse STL containers.
#include <iostream> #include <map> int main() { std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}}; for (auto it = (); it != (); ++it) { std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl; } return 0; }
In this example,it
is an iterator pointing tostd::map
elements in .it->first
andit->second
Access keys and values separately.
3. Use a reverse iterator
If you want tostd::map
The end of starts traversal, and you can use a reverse iterator.
#include <iostream> #include <map> int main() { std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}}; for (auto it = (); it != (); ++it) { std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl; } return 0; }
Reverse iterators work similarly to forward iterators, but they start at the end of the container and move forward.
Things to note
- During the traversal, do not modify the size of the container (for example, do not insert or delete elements), as this may cause the iterator to fail.
- If you only need to iterate over keys or values, not key-value pairs, you can use
std::map::keys()
orstd::map::values()
(C++20 and above) to get the views of keys or values and iterate over them. However, please note that these methods are not available in pre-C++20 standards.
Which traversal method to choose depends on your specific needs and the C++ standard version. Range for loops are usually the cleanest and modern way, but iterators offer more flexibility and control.
This is the end of this article about the implementation example of C++ traversal map. For more related C++ traversal map content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!