The range-based for loop is a concise and powerful Iterator traversal mechanism that has been introduced in C 11 introduced in. It is used to iterate over a container or other iterable sequence and reference elements in the sequence through one or more variables. Here's how to use a range-based for loop correctly:
for (auto elem : container) { // 代码体 }
Where:
When using a range-based for loop, you can choose one of the following three element capture modes:
Range-based for loops can be used for two main purposes:
To correctly use range-based for For loops, consider the following guidelines:
for (const auto& elem : container) // 按引用捕获常量
for (auto& elem : container) // 按引用捕获
for (auto&& elem : container) // 按引用捕获 proxy
In generic code, it is recommended to use const auto&elem to capture elements for observation, and auto&&elem captures elements for modification, as these methods work with various types of containers and elements.
The above is the detailed content of How Can I Correctly Use Range-Based For Loops in C 11?. For more information, please follow other related articles on the PHP Chinese website!