Using Range-Based for() Loops with std::map
Range-based for() loops in C 11 and beyond provide a convenient way to iterate over containers. While examples often showcase simple containers like vectors, confusion arises when using them with more complex data structures such as maps.
When using a range-based for() loop with a map, the element type is not as straightforward as it seems. Consider the following example:
<code class="cpp">std::map<foo, bar> testing = { /*...blah...*/ }; for (auto abc : testing) { std::cout << abc << std::endl; // ? should this give a foo? a bar? std::cout << abc->first << std::endl; // ? or is abc an iterator? }
Unlike vectors, where the loop variable is the type of the container's element (e.g., int), the loop variable abc for a map is actually of the type std::pair In C 17 and later, you can directly access the key and value using structured bindings: In C 11 and C 14, you can still iterate over the map using the enhanced for loop, but you have to manually extract the key and value: It's important to understand that the loop variable abc or kv in these examples is not an iterator. Instead, it represents a copy of the pair containing the key and value of the current map element. This distinction is crucial when considering modifications or references to the map elements within the loop. The above is the detailed content of How do Range-Based for() Loops Work with std::map in C ?. 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>