正常
Range-Based for Loop (C++11)
In a nutshell
Syntactic sugar that lets us iterate over every element of a container or array without hand-writing iterators, making loop code more concise and less error-prone.
Header file
None (language feature)
Core API Cheat Sheet
| Operation | Signature | Description |
|---|---|---|
| Read-only traversal | for (auto item : range) | Copies each element into item |
| Reference traversal | for (auto& item : range) | Accesses elements via lvalue reference (modifiable) |
| Const reference traversal | for (const auto& item : range) | Avoids copies and prevents modification |
| Init statement | for (init; auto& item : range) | Runs initialization before the loop starts (since C++20) |
| Array traversal | for (auto item : arr) | Works with native arrays of known size |
Minimal Example
C++
#include <vector>
#include <iostream>
// Standard: C++11
int main() {
std::vector<int> v = {1, 2, 3};
for (const auto& x : v) {
std::cout << x << ' ';
}
return 0;
}Embedded Applicability: High
- Zero-overhead abstraction: compiles to code fully equivalent to a hand-written iterator or index loop, with no extra runtime cost
- The concise syntax cuts down on bugs caused by out-of-bounds indices or invalidated iterators
- Also very practical for compile-time traversal of
constexprarrays - Caution: when the range comes from a member function returning a temporary, watch out for lifetime issues (UB before C++23)
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 4.6 | 3.0 | 2012 |
See Also
Part of the content is referenced from cppreference.com and is licensed under CC-BY-SA 4.0