What is const_iterator in C++ STL Containers?
Last Updated :
09 Feb, 2024
In C++ STL, a const_iterator is also an iterator and is used similarly to a regular iterator but its main purpose is to iterate over the elements of the container without actually modifying them in any way. It is similar to passing constant pointers to a function.
In this article, we will learn what are constant iterators, how to use them in the STL containers, and how they are different from regular iterators.
How to Use const_iterator?
Every container in C++ provides two member functions: cbegin() and cend() that returns the constant iterator to the beginning and end of the container, respectively. We can use these constant iterators to traverse the container. But we keep in mind that they only allow users to read the value not modify it.
Also, if we have a constant container, then we can only use the constant iterator to traverse it.
C++ Program to Iterate Using const_iterator
The below example demonstrates the use of const_iterator to iterate over an STL container vector.
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 10, 20, 30, 40, 50 };
for (vector< int >::const_iterator it = myVector.cbegin();
it != myVector.cend(); ++it) {
cout << *it << " " ;
}
return 0;
}
|
Explanation: In the above example cbegin() is used to point at the beginning of the vector and cend() points one past the end of the vector and loop iterates over the vector using the printsr and prints the vector elements.
Share your thoughts in the comments
Please Login to comment...