Home >Backend Development >C++ >How do Range-Based for() Loops Work with std::map in C ?

How do Range-Based for() Loops Work with std::map in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 03:27:291161browse

 How do Range-Based for() Loops Work with std::map in C  ?

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. This means that abc holds a pair containing both the key and value of the map.

In C 17 and later, you can directly access the key and value using structured bindings:

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

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:

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

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!

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