Unordered sets can be defined for any inbuilt or user-defined data structure.
These sets are implemented using hash tables, where each entry is randomly added to the table to achieve a time complexity of .
The following code shows how unordered sets can be defined for strings.
A similar method can be used for any predefined data structure.
data_type
is the predefined data type e.g., stringset_name
is the name of the set//declaring a setunordered_set <data_type> set_name;
The complete code for declaring and inserting values in an unordered set is given below.
#include <iostream>#include <bits/stdc++.h>using namespace std;int main() {unordered_set <string> fruits; // declare stringcout<< fruits.empty() << endl; //check if set is emptyfruits.insert("Apple"); //add elements to setfruits.insert("Banana");fruits.insert("Cantaloupe");for (auto i: fruits) // print all the elemnts in setcout<< i <<endl;return 0;}
Unordered sets can be implemented on user-defined data structures as well.
The following code shows how to declare an unordered set using user-defined data structures.
One key thing to remember is that the comparison function needs to be defined to let the compiler know how the keys will be compared. Without the function, the compiler will generate an error.
Hash functions also need to be defined for the given data type.
Unordered sets can be created in the following way:
data_type
is the user-defined data structuredata_hash_function
is the hash function that will be usedset_name
is the name of the set// This method declares an unordered set using the user-defined data type and user-defined hash functionunordered_set (data_type, data_hash_function) set_name;
The complete code for defining and inserting elements is given below.
#include <iostream>#include <string>#include <bits/stdc++.h>using namespace std;class fruits{ //declare a classpublic:string name;string color;//This is the comparison operator.bool operator==(const fruits &f) const{return (this->name == f.name);}};//create a class to produce the hash that we will useclass fruits_hash{public:size_t operator() (const fruits & f) const{return f.name.length();}};int main() {//declare objects of class fruitsfruits f1 {"Apple", "red"};fruits f2 {"Banana", "yellow"};//declare unordered setunordered_set <fruits, fruits_hash> my_fruits;//insert objects to setmy_fruits.insert(f1);my_fruits.insert(f2);//print setfor (auto i: my_fruits)cout<< "Name: " << i.name << ", Color: " << i.color <<endl;return 0;}
Free Resources