Home >Backend Development >C++ >How to Choose the Right C 11 Range-Based `for` Loop Syntax?
Understanding Range-Based for Syntax in C 11
Range-based for loops in C 11 provide a simplified syntax for iterating over containers. The syntax varies depending on whether you intend to observe or modify the container's elements.
For Observing Elements
To observe elements without modifying them, the recommended syntax is:
for (const auto& elem : container)
This syntax captures the elements by const reference, avoiding unnecessary copies in cases where the objects are expensive to copy.
For Modifying Elements
If you need to modify elements in place, the syntax is:
for (auto& elem : container)
This syntax captures the elements by non-const reference, allowing you to modify them in the loop body.
Special Case: Proxy Iterators
However, for containers that use proxy iterators (such as std::vector
for (auto&& elem : container)
This syntax uses the "&&" type modifier to correctly work with proxy iterators.
Summary
The above is the detailed content of How to Choose the Right C 11 Range-Based `for` Loop Syntax?. For more information, please follow other related articles on the PHP Chinese website!