![]() |
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
|
// C++ program to use of const_iterator to iterate over a // STL container. #include <iostream> #include <vector> using namespace std; int main() { // creating STL container: vector vector< int > myVector = { 10, 20, 30, 40, 50 }; // Using const_iterator to iterate over the vector and // print it's value for (vector< int >::const_iterator it = myVector.cbegin(); it != myVector.cend(); ++it) { cout << *it << " " ; } return 0; } |
10 20 30 40 50
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.
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |