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


In this example, we have used the std::list library that provides an implementation of the list data structure in C++.

#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


Range-based for loops is very similar to the for loops we know in C++ and many other languages. It executes a loop over a range. It is an improvement in the implementation and calling convention.

Syntax

for( range_declaration : range_expression ) loop_statement
#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