Professional Documents
Culture Documents
Unorder Set
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;
}
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.