Home  >  Article  >  Backend Development  >  How does range-based iteration work with standard maps in C and how does the syntax differ across versions?

How does range-based iteration work with standard maps in C and how does the syntax differ across versions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 02:49:28980browse

How does range-based iteration work with standard maps in C   and how does the syntax differ across versions?

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. This means that each element represents a key-value pair rather than an individual key or value.

To retrieve the key and value separately, you can use the first and second members of the pair:

<code class="cpp">for (auto abc : testing) {
  std::cout << abc.first << " has value " << abc.second << std::endl;
}</code>

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:

<code class="cpp">for (const auto& [key, value] : testing) {
  std::cout << key << " has value " << value << std::endl;
}</code>

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

  • It's possible to modify the map's contents within the loop using reference variables declared as auto&:
<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>
  • If the map's values are large, it may be more efficient to use a range-based loop with iterators instead of pair objects. However, this eliminates some of the convenience provided by range-based for loops.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn