-->

C++ - List Part 3: Iterating Over a List

Lists can be traversed using iterators, range-based loops, or while loops.

Examples and Explanation

Using Iterators

for (std::list<int>::iterator it = myList.begin(); it != myList.end(); ++it) {

    std::cout << *it << " ";

}

Explanation: Iterators provide sequential access to list elements, allowing safe traversal.

Using a Range-Based For Loop

for (int val : myList) {

    std::cout << val << " ";

}

Explanation: Range-based loops simplify iteration for read-only or modification operations.

Reversing Iteration

for (auto it = myList.rbegin(); it != myList.rend(); ++it) {

    std::cout << *it << " ";

}

Explanation: Use reverse iterators (rbegin and rend) to iterate in reverse order.