Home >Backend Development >C++ >How do I iterate through a std::map using range-based for loops in C 11 and later?

How do I iterate through a std::map using range-based for loops in C 11 and later?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 17:34:31411browse

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::value_type, which is essentially a std::pair. This means:

For C 17 and later:

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

For C 11 and C 14:

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

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!

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