Different Ways to iterate through a List in C++

In this article, we will learn different ways to iterate through a List in C++ language.std::list provides us with the implementation of list data structure in C++. This is part of the STL std library.


Different ways iterate through a list in c++


  1. Iterate std::list using Iterators.
  2. using c++11 Range Based For Loop
  3. using std::for_each and Lambda Function.

1. Iterate through std::list using Iterators


#include <list>
#include <iostream>
#include <string>
#include <iterator>

using namespace std;

int main()
{
    std::list<string> Playerlist =
    { "Sachin", "Dravid", "Lara", "Dhoni" };
			
			
    std::cout << "The Players in the List are: " << std::endl;
	
    for (auto it = Playerlist.begin(); it != Playerlist.end(); it++)
    {
        std::cout << *it  << std::endl;
    }
    
    return 0;
}

Output

The Players in the List are: 
Sachin
Dravid
Lara
Dhoni

2. using c++11 Range Based For Loop


#include <list>
#include <iostream>
#include <string>
#include <iterator>

using namespace std;

int main()
{
    std::list<string> Playerlist =
    { "Sachin", "Dravid", "Lara", "Dhoni" };
			
			
    std::cout << "The Players in the List are: " << std::endl;
	
    for (auto elem : Playerlist)
    {
        std::cout << elem << std::endl;
    }
    
    return 0;
}

Output

The Players in the List are: 
Sachin
Dravid
Lara
Dhoni

3. using std::for_each and Lambda Function


Only C++ 14 onwards

#include <list>
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
using namespace std;

int main()
{
    std::list<string> Playerlist =
    { "Sachin", "Dravid", "Lara", "Dhoni" };
			
			
    std::cout << "The Players in the List are: " << std::endl;
	
    std::for_each(Playerlist.begin(), Playerlist.end(),
            [](auto & elem)
            {
                std::cout << elem << std::endl;
            });
		
    
    return 0;
}

Output

The Players in the List are: 
Sachin
Dravid
Lara
Dhoni