In this article we will discuss different ways to iterate through std::list of objects.

Suppose we have a struct Player that contains id and name i.e.

Lets create a list Player objects i.e.

Now we will iterate through list of Player objects using different techniques i.e.

Iterating through list using Iterators

Steps:

  • Create an iterator of std::list.
  • Point to the first element
  • Keep on increment it, till it reaches the end of list.
  • During iteration access, the element through iterator

Iterating through list using std::for_each and Lambda Function

std::for_each is an STL algorithm that accepts a range and a function i.e.

It iterates over the given range and passes each element in range to the passed function fn.

We will pass begin() and end() of list as range arguments and lambda function as third argumen i.e.

Iterating through list using c++11 Range Based For Loop

Iterating through list in Reverse Order using reverse_iterator

  • list::rbegin() returns a reverse_iterator which points to the end of list
  • list::rend() returns a reverse_iterator which points to the beginning of list

reverse_iterator will iterate in backwards only.

Complete executable example is as follows,

Output

To compile above code on linux use following command,

g++ –std=c++11 example.cpp

Click Here to Subscribe for more Articles / Tutorials like this.