Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-10-27 17:34:31
Original
325 people have browsed it

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;
}
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!