Home >Backend Development >C++ >What is the Value Type of the Variable in a Range-Based for() Loop with std::map?
Range-Based for() Loops with std::map: Dissecting the Value Type
When utilizing range-based for() loops with std::map, comprehension of the value type of the variable becomes crucial. In C 11 and above, range-based loops provide direct access to individual elements within a container. However, when dealing with maps, the type of variable in such loops may require further clarification.
Within std::map, each element is represented by std::pair
C 17 and Higher
In C 17 and higher, enhanced range-based for() loops enable concise and elegant iteration over std::map. Here, the variable is declared as a tuple containing the key and value:
<code class="cpp">for (auto& [key, value]: myMap) { // Access key and value directly }</code>
C 11 and C 14
In C 11 and C 14, enhanced for loops can be used, but the key and value need to be extracted manually from each std::pair:
<code class="cpp">for (const auto& kv : myMap) { // Extract key and value manually: auto key = kv.first; auto value = kv.second; }</code>
Understanding the Value Type
The key takeaway is that the value type in range-based for() loops with std::map is std::pair
The above is the detailed content of What is the Value Type of the Variable in a Range-Based for() Loop with std::map?. For more information, please follow other related articles on the PHP Chinese website!