Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C++ - ITERATING SET


There are many ways by which we can Iterate a set.


So we have a set with values, Tom, John and C++.


Now, let us see the first and easiest way to iterate a set.


Iterating a set using 'for range' loop


Example :



#include <iostream>
#include <set>

using namespace std;


int main() {
        
    set<string> x; 
        
    x.insert("Tom");
    x.insert("John");
    x.insert("C++");
        
    for (string i : x)  
    {  
        cout << i << endl;  
    }
        
    return 0;    
}


Output :



  C++
  John
  Tom

Similarly, in the above code we have created a set.


set<string> x;

And initialised to the variable x. And as we know the elements in a Set are inserted in Sorted order.

java_Collections

In the next line we have used the for loop to Iterate through the set.


for (string i : x)
{
	cout << i << endl;
}

Now, if we see the iterations of for loop,


for (string i : x)
{
	cout << i << endl;
}

1st Iteration


In the first Iteration the first value of the set x (i.e. C++) is taken and put into the variable i.

java_Collections

And the print statement, prints the value of i.

Output :



  C++

2nd Iteration


Similarly, in the second Iteration the second value of the set x (i.e. John) is taken and put into the variable i.

java_Collections

And the print statement, prints the value of i.

Output :



  C++
  John

3rd Iteration


Similarly, in the third Iteration the third value of the set x (i.e. Tom) is taken and put into the variable i.


And the print statement, prints the value of i.

Output :



  C++
  John
  Tom