Range-Based Loops (C++11)
Range-based loops is a feature added to C++ in the C++11 standard. It provides a simpler and more expressive way to iterate over the elements of a container, such as an array or a standard library container. Here's an example:
#include <vector> #include <iostream> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; for (int x : vec) { std::cout << x << " "; } std::cout << std::endl; return 0; }
In this example, we use a range-based loop to iterate over the elements of a vector. The syntax of the loop is to declare a variable x
that will hold the value of each element in the vector, followed by a colon :
and the name of the container we want to iterate over (vec
in this case).
The loop iterates over the elements of the vector and assigns each element to the variable x
. We can then use the value of x
inside the loop body, which in this example is just printing the value of x
to the console.
Range-based loops can be used with any container that supports the begin
and end
functions, including arrays, standard library containers such as std::vector
and std::map
, and user-defined containers that provide the necessary functions.
One advantage of range-based loops over traditional loops is that they make the code more concise and easier to read, especially when iterating over the elements of a container. They also help prevent errors related to off-by-one errors or iterator invalidation, which can occur when using traditional loops.
Overall, range-based loops are a useful feature that can simplify your code and make it easier to understand.