Open In App

How to Traverse a List with const_iterator in C++?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a list is a container used to store data in non-contiguous memory locations. It also provides a constant iterator that provides the constant reference to its elements. In this article, we will discuss how to traverse a list with const_iterator in C++.

Example

Input: 
myList = {10,20,30,40,50}

Output:
10 20 30 40 50

Iterate a List with const_iterator in C++

In C++, const_iterator provides a constant reference to the container elements. It means that we can only access the value but cannot modify it. It is useful to prevent unintended changes that may occur while traversing.

To iterate a std::list with const_iterator in C++, we can use the std::list::cbegin() and std::list::cend() functions that give the constant iterator to the beginning and the end of the list.

C++ Program to Iterate a List with const_iterator

The following program illustrates how we can traverse a list with const iterator in C++:

C++
// C++ program to illustrate how to traverse the list using
// the const_iterator
#include <iostream>
#include <list>
using namespace std;

int main()
{
    // Initializing a list
    list<int> myList = { 10, 20, 30, 40, 50 };

    // Using const_iterator to iterate through the list
    // elements
    for (auto i = myList.cbegin(); i != myList.cend();
         i++) {
        cout << *i << " ";
    }
    cout << endl;

    return 0;
}

Output
10 20 30 40 50 

Time complexity: O(N), where N is the number of elements in the list.
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads