Home >Backend Development >C++ >How do I iterate through a std::map using range-based for loops in C 11 and later?
Range-Based for() Loop with std::map
In C 11 and later versions, range-based for() loops offer a convenient way to iterate through containers. When iterating over simple containers like vectors, each element is readily accessible as the loop variable. However, for complex containers such as maps, understanding the type of the loop variable becomes crucial.
Consider the following code snippet:
<code class="cpp">std::map<foo, bar> testing = { /*...blah...*/ }; for (auto abc : testing) { std::cout << abc << std::endl; std::cout << abc->first << std::endl; }
In this scenario, each element is a std::map For C 17 and later: For C 11 and C 14: Alternatively, you could mark kv as const for a read-only view of the values. The above is the detailed content of How do I iterate through a std::map using range-based for loops in C 11 and later?. For more information, please follow other related articles on the PHP Chinese website!<code class="cpp">for (auto& [key, value] : myMap) {
std::cout << key << " has value " << value << std::endl;
}</code>
<code class="cpp">for (const auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}</code>