How to Traverse a Set with const_iterator in C++?
Last Updated :
21 Feb, 2024
In C++, sets are a type of associative container in which each element has to be unique because the value of the element identifies it. It contains a constant iterator that provides the constant reference to its elements. In this article, we will discuss how to traverse a set with const_iterator in C++ STL.
Example
Input:
input_set = {70,10,50,90,60,40,100,30,20,80}
Output:
10, 20, 30, 40, 50, 60, 70, 80, 90, 100
Traverse a Set with const_iterator 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.
The std::set class contains 4 functions that return the constant iterators:
- std::set::cbegin(): Return a const iterator that points to the first element of the set.
- std::set::cend(): Return a const iterator that points just after the last element of the set.
- std::set::crbegin(): Return a const reverse iterator that points to the reverse first element (last element) of the set.
- std::set::crend(): Return a const reverse iterator that points just after the reverse last element(first element) of the set.
We can use the above function to get the constant iterators and traverse the set using loops.
C++ Program to Traverse a Set with const_iterator
C++
#include <iostream>
#include <set>
using namespace std;
void display(set< int > set1)
{
set< int >::const_iterator c_itr;
for (c_itr = set1.cbegin(); c_itr != set1.cend();
c_itr++) {
cout << *c_itr << ", " ;
}
}
int main()
{
set< int > set1;
set1.insert(70);
set1.insert(10);
set1.insert(50);
set1.insert(90);
set1.insert(60);
set1.insert(40);
set1.insert(100);
set1.insert(30);
set1.insert(20);
set1.insert(80);
display(set1);
return 0;
}
|
Output
10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
Time complexity: O(N), where N is the number of elements in the set.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...