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




C++ - SET


A set is a Collection that can also hold multiple values. And elements in a set are sorted and doesn't allow duplicate values.


A set is created in the same way a List is created.


set<string> x;

The above set is used to hold values of string type.


Creating an empty set


Example :



#include <iostream>
#include <set>

using namespace std;

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


Output :



  C++
  John
  Tom

In order to use set in your code, the first thing you need to dos is, include Set in your code.


#include <set>

So, in the above code, we have declared an empty set that is used to hold values of string data type.


set<string> x;

Then we have used the insert() method to add the values to the set.


x.insert("Tom");
x.insert("John");
x.insert("C++");

And finally, used the for loop to print the contents of the set.


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

Elements in a Set are sorted


Now, if you look at the above output,

Output :



  C++
  John
  Tom

The elements are printed in Sorted order(i.e. Ascending order). That is because the elements in a Set are stored in soted order.


Set doesn't accept duplicates


Example :



#include <iostream>
#include <set>

using namespace std;


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


Output :



  C++
  John
  Tom

So, in the above code we have created a set using the values, "Tom", "John", "C++" and "John".


set<string> x;

Now, if we see the output,

Output :



  C++
  John
  Tom

You can see only three values are printed.


This is because in the above set, the name John is present twice.


And since a set doesn't accept duplicates, the name John is not inserted to the set twice.


And we see the above output with John present only once.