Range-Based Iteration of Standard Maps
In C 11 and beyond, range-based for() loops offer a convenient syntax for iterating through containers. However, their behavior with complex data structures like maps can be confusing.
Consider the following example:
<code class="cpp">std::map<foo, bar> testing = /*...initialized...*/; for (auto abc : testing) { std::cout << abc << std::endl; }
What is the type of abc in this loop? Would it yield a foo key, a bar value, or an iterator?
Resolution
In C 11 and C 14, range-based loops iterate over a map's key-value pairs. The type of abc is therefore std::pair To retrieve the key and value separately, you can use the first and second members of the pair: Note that the variables in the loop are typically declared as const to signify that they will not modify the map's contents. C 17 and Beyond In C 17, a convenient shorthand notation is introduced for range-based iteration of maps: This syntax replaces the first and second members with key and value directly. This allows for a cleaner and more concise expression of iteration over key-value pairs. Additional Considerations The above is the detailed content of How does range-based iteration work with standard maps in C and how does the syntax differ across versions?. For more information, please follow other related articles on the PHP Chinese website!<code class="cpp">for (auto abc : testing) {
std::cout << abc.first << " has value " << abc.second << std::endl;
}</code>
<code class="cpp">for (const auto& [key, value] : testing) {
std::cout << key << " has value " << value << std::endl;
}</code>
<code class="cpp">for (auto& kv : testing) {
std::cout << kv.first << " had value " << kv.second << std::endl;
kv.second = "modified"; // Modifies the map's value
}</code>