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.
#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;
}
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;
}Now, if you look at the above output,
The elements are printed in Sorted order(i.e. Ascending order). That is because the elements in a Set are stored in soted order.
#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;
}
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,
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.