Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

unorder_set

===============
It is internally implemented using a hash table where values are stored on the
indices basis. All operation on the unorder_list takes constant time O(1) on an
average which can go upto lineat time O(n) in worst case, it dependents on the
internally used hash function. But, practically it perform very well.

example - 1
#include <iostream>
#include <unordered_set>
using namespace std;

int main(){
// declare the unordered_set
unordered_set<string> languages;
// insert value into unordered_set
languages.insert("C++");
languages.insert("Java");
languages.insert("Python");
languages.insert("Swift");
languages.insert("Dart");
languages.insert("Swift");
// total number of elements present in unordered_list
cout << endl << "size of unordered_list : " << languages.size();
// display all elements from unordered_list
for(auto element : languages){
cout << endl << element;
}
// find "Dart" from the list
// find() methods retur the end elements iterator if no specifie key is
available in the list. otherwise it returns iterator of that elements.
string key = "Dart";
if(languages.find(key) == languages.end()){
cout << endl << "Element \"Dart\" is not present in the list";
}
else {
cout << endl << "Element \"Dart\" is present in the list";
}

return EXIT_SUCCESS;
}

example - 2 (display duplicate elements from array using unordered_list)


#include <iostream>
#include <unordered_set>
using namespace std;

void printDuplicate(int arr[], int count){

// declare unordered_set to store the unique element


unordered_set<int> intset;
// declare unordered_set to store the duplicate element from array
unordered_set<int> duplicate;

for ( int i = 0; i < count; ++i ) {


// duplicate elements are not found
if(intset.find(arr[i]) == intset.end()) {
intset.insert(arr[i]); // if duplicate element is not present then it
store in this unordered_set
}
else {
// if duplicate element present in the array then
duplicate.insert(arr[i]);
}
}

// display the duplicate element


unordered_set<int> :: iterator it;
for(it = duplicate.begin(); it != duplicate.end(); ++it) {
cout << endl << *it;
}
}

int main() {
// declare and initialize array
int arr[] = {1, 5, 2, 1, 4, 3, 1, 7, 2, 8, 9, 5};
// calculate the length of array
int count = sizeof(arr)/sizeof(arr[0]);
// print duplicate element
printDuplicate(arr, count);
return EXIT_SUCCESS;
}

set vs unordered_set
===============================
1) In set value are stored into specific ordered where as unordered_set values are
not any specific ordered.
2) Set is implemented as balanced tree structure that is why it is stored value in
specific ordered where as unordered-set is implemented as hash table so value are
store based on the hash function.
3) the time complexity of set operation is O(log n) while for unordered_set, it is
O(1) on an average case.

You might also like