Accessing array elements using indexing becomes quite hard, C++ provides range based for loop as a remedy. For example,
#include <iostream>
#include <vector>
int main(int argc, char const *argv[])
{
std::vector items{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "Iterating over ints\n";
for (int item : items) // better to use auto instead of int
{
std::cout << item << "\n";
}
return 0;
}It looks very clean as we do not have to deal with any indices and we can focus on the problem we are trying to solve instead.
How it works?
Range based for loop iterates over the array elements by copying the element to the given variable in the declaration in each iteration. It then executes the block.
If there are no elements in the array, the block does not get executed.
Using references to avoid expensive copy
As loop copy the element to the variable, if the type used is expensive to copy (such as std::string), looping through the elements can be inefficient.
We can avoid that using reference for the declared variable. For example,
std::vector<std::string> names{"Hemant", "Mitesh", "John", "Rehan"};
for (const auto &name : names) // using reference to avoid making copy
{
std::cout << name << "\n";
}Support with other containers
Range based loop works for most of the arrays such as std::vector, std::array, (non-decay) C-style array, linked lists, trees, and maps.
However, it does not work with decayed C-style arrays because loop requires array length information to know when to complete the traversal and decayed C-style does not provide this.
Range based loops also do not work with enumerations.