Since C++11, we can write:
vector<int> v{1, 2, 3, 4}; for (auto x : v) { cout << x << endl; }
According to Essentials of Modern C++ Style, the following code will soon be also legal in C++:
vector<int> v{1, 2, 3, 4}; for (x : v) { cout << x << endl; }
Will this feature be available in C++17 or C++20?
Range-based for loop in C++ It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .
Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once. Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).
No. This was killed by the committee more than two years ago, mostly because of concerns about potential confusion caused by shadowing:
std::vector<int> v = { 1, 2, 3, 4 }; int x = 0; for(x : v) {} // this declares a new x, and doesn't use x from the line above assert(x == 0); // holds
The objections came up so late in the process that both Clang and GCC had already implemented the feature by the time it got rejected by the full committee. The implementations were eventually backed out: Clang GCC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With