8 ways to iterate a container in C++
5 min read
You can try the below examples in C++ Shell.
1. Traditional for loop
It is the oldest way to iterate over a container.
It was part of the C language and was later included in C++ when it was created.
This for loop variant uses the index to access the elements of the array.
2. While loop
Same as the previous example, but using a while (or do while) loop and the initialization of the index variable happens outside the loop.
The index is incremented inside the loop, at the end of each iteration.
3. Pointer arithmetic
It is a low-level way to iterate over an array and is usually not good practice because of potential out-of-bounds errors. The pointer is incremented at the end of each iteration to move to the next element.
4. Goto statement
I am giving this example just for the sake of completeness. It is not recommended to use goto statements in C++ because it can make the code hard to read and understand.
5. Iterator-based for loop
Works with any container that supports begin() and end() methods. This includes C-style arrays.
6. Range-based for loop
The recommended and modern way of iterating a container.
It’s safe, clean and works with any container that supports begin() and end().
7. Functional style
In this example, we use for_each from the <algorithm> header. This approach allows you to pass a lambda function or a function pointer to be executed for each element in the range.
8. Recursion
It’s rarely used in practice, but it can be discussed in theoretical contexts.