C 11 introduced range-based for loops as a concise and expressive way to iterate over containers. The syntax is:
for (range_declaration : container) { // body of the loop }
where:
The variable in the range_declaration can be captured by reference or value using the following syntax:
For observing the elements, where you don't need to modify them, you should use const auto&. This prevents unnecessary copies and ensures that the original elements are not modified.
If you want to modify the elements, use auto&.
Note that for containers with proxy iterators (like std::vector
Consider the following guidelines when using range-based for:
For observing elements:
For modifying elements:
In generic code, where you don't know the type of the elements being iterated over, use:
The above is the detailed content of How Do I Effectively Use Range-Based For Loops in C 11?. For more information, please follow other related articles on the PHP Chinese website!