Open In App

How to Traverse Vector using const_iterator in C++?

In C++, a const_iterator is a type of iterator that points to constant content means by using a const_iterator, we can read from but cannot write to the element it points to. In this article, we will learn how to use a const_iterator with a vector in C++ STL.

Example:

Input: 
myVector = {1, 2, 3}

Output:
result: {1, 2, 3}

Iterating Over a Vector Using const_iterator in C++

We can get the const_iterator to a std::vector container using the std::vector::cbegin() and std::vector::cend() functions that return a const_iterator pointing to the beginning and the end of the vector, respectively. We can use constant iterators when we do not want to modify the data in the vector or the vector itself is constant.

C++ Program to Iterator Over a Vector Using const_iterator

The below program illustrates how we can iterate over a vector using const_iterator in C++.

// C++ Program to illustrate how we can iterate over a
// vector using const_iterator
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Creating a vector of int
    vector<int> myVector = { 1, 2, 3 };

    // Declaring a const_iterator to the vector
    vector<int>::const_iterator it;

    // Displaying vector elements using const_iterator
    cout << "Vector Elements: ";
    for (it = myVector.cbegin(); it != myVector.cend();
         ++it) {
        cout << *it << " ";
    }

    return 0;
}

Output
Vector Elements: 1 2 3 

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



Article Tags :