We know generally that Sets are unordered collection of unique/distinct elements, then why are the elements in set and Multiset of C++ always ordered in ascending order?
Is it always like this? Why?
Set and Multiset related Concepts
No, there is unordered_set also, whose elements are not sorted. But why to use set when you can use array or vector for that purpose too. Set is created so that it will be easier for the programming to find unique elements in a certain order.
Now talking about unordered set. Its can be used as in the example below
// C++ program to demonstrate various function of unordered_set
#include <bits/stdc++.h>
using namespace std;
int main()
{
// declaring set for storing string data-type
unordered_set <string> stringSet ;
// inserting various string, same string will be stored
// once in set
stringSet.insert("code") ;
stringSet.insert("in") ;
stringSet.insert("c++") ;
stringSet.insert("is") ;
stringSet.insert("fast") ;
string key = "slow" ;
// find returns end iterator if key is not found,
// else it returns iterator to that key
if (stringSet.find(key) == stringSet.end())
cout << key << " not found" << endl << endl ;
else
cout << "Found " << key << endl << endl ;
key = "c++";
if (stringSet.find(key) == stringSet.end())
cout << key << " not found\n" ;
else
cout << "Found " << key << endl ;
// now iterating over whole set and printing its
// content
cout << "\nAll elements : ";
unordered_set<string> :: iterator itr;
for (itr = stringSet.begin(); itr != stringSet.end(); itr++)
cout << (*itr) << endl;
}
output:
slow not found
Found c++
All elements :
is
fast
c++
in
code
if you think i cleared your doubt, you can mark this as resolved. Thanks😊
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.