Skip to main content

C++ STL Unordered Set – std::unordered_set

In this tutorial you will learn about stl unordered set container in c++ and various functions applicable on it.

Unordered Set comes under unordered containers. As we discussed in introduction to stl article, unordered containers internally implemented with hash tables. Each item calculated by hash function, to map to hash table. The main advantage is if we have effective hash function we can find elements in O (1) time. On average it can go to linear time. Simply we can say it’s based on type of hash function used.

So we can say these are fastest among all containers.

As name says that in unordered_set the order is not defined. Unordered set doesn’t allow duplicates.

C++ STL Unordered Set – std::unordered_set

Useful iterators to work on this unordered set:

begin(): returns iterator to the beginning

end(): returns iterator to the end of the list

cbegin(): returns constant iterator to the beginning

cend(): returns constant iterator to the end.

First we need to include unordered_set header file. Which is #include<unordered_set>

Inserting element into unordered_set:

There are various ways to insert elements into unordered_set.

Method 1: Insert directly by passing element.

UnOrdSet.insert(element);

Method 2: Using iterator. This returns iterator at inserted position.

UnOrdSet.insert ( iterator, value)

Method 3: Copying from another container.

Example program to insert into unordered_set:

#include<iostream>
#include <unordered_set>

using namespace std;

int main(){
        unordered_set<int> s1; // declaring unordered_set
        unordered_set<int> :: iterator it; // iterator for unordered_set
        
        for(int i=0;i<5;i++){
                s1.insert(i*10); // inserting using Method1
        }
        
        it= s1.begin();
        s1.insert(it,99);
        
        int ary[]= { 23, 34, 45, 56};
        s1.insert(ary, ary+4); // Inserting using method3
        
        //checking by printing
        for(it= s1.begin(); it!=s1.end(); it++) cout << *it << " ";
        
        // We can observe that output will be print in sorted order. That is the property of Unordered_set
        
        return 0;
}

Output

56 45 34 23 40 99 0 10 20 30

Modifiers: The functions which effect size/data of that container

erase(): We can erase an element by specifying value or pointing to iterator.

swap(): swaps elements of Unordered_set1 to Unorderedset2 and Unorderedset2 to Unordered_set1.

clear(): removes all elements in the list. It results list of size 0.

Example program to show above functions:

#include<iostream>
#include<unordered_set>

using namespace std;

int main(){
        unordered_set<int> s1;
        unordered_set<int> :: iterator it;
        
        for(int i=0; i<5; i++) s1.insert(i+10);
        s1.erase(12); // deleting element 12
        cout << "elements after deleting  12 -->";
        for(it= s1.begin(); it!=s1.end(); it++) cout << *it << " ";
        cout << endl;
        
        unordered_set<int> s2;
        for(int i=0;i<4;i++) s2.insert(i);
        
        cout << "unordered_set 1 elements before swapping -->";
        for(it= s1.begin(); it!= s1.end(); it++) cout<< *it << " ";
        cout << endl;
        
        cout << "unordered_set 2 elements before swapping -->";
        for(it= s2.begin(); it!= s2.end(); it++) cout<< *it << " ";
        cout << endl;
        
        s1.swap(s2); // swapping operation

        cout << "unordered_set 1 elements after swapping -->";
        for(it= s1.begin(); it!= s1.end(); it++) cout<< *it << " ";
        cout << endl;
        
        cout << "unordered_set 2 elements after swapping -->";
        for(it= s2.begin(); it!= s2.end(); it++) cout<< *it << " ";
        cout << endl;

        s1.clear(); // clearing list 1
        cout << "Performing clear() operation on unordered_set1......" << endl;
        s1.empty() ? cout <<"Unordered_set is empty" << endl: cout << "unordered_set is not empty" << endl; //
        // ternary operation which resutls list is empty or not
        
        return 0;
}

Output

elements after deleting 12 –>14 10 11 13
unordered_set 1 elements before swapping –>14 10 11 13
unordered_set 2 elements before swapping –>3 2 1 0
unordered_set 1 elements after swapping –>3 2 1 0
unordered_set 2 elements after swapping –>14 10 11 13
Performing clear() operation on unordered_set1……
Unordered_set is empty

Information retrieving functions:

empty(): returns a Boolean value whether Unordered_set is empty or not.

size(): returns the size of the Unordered_set.

max_size(): returns the maximum size a Unordered_set can have.

And some more operations are:

find(): It returns iterator to the element.

count(x):  Returns how many times elements “x” present in Unordered_set.

Example program to show above functions:

#include<iostream>
#include<unordered_set>

using namespace std;

int main(){
        unordered_set<int> s1;
        unordered_set<int> :: iterator it;
        
        for(int i=0; i<5; i++) s1.insert(i+10);
        s1.empty() ? cout <<"Unordered_set is empty" << endl: cout << "unordered_set is not empty" << endl;
        cout << "size of the unordered_set is " << s1.size() << endl;
        cout << "maximum size of the unordered_set is " << s1.max_size() << endl;
        cout << "finding elemnt 12 in unordered_set" << endl;
        it= s1.find(12);
        cout << *it << endl;
        
        s1.insert(12);
        if(s1.count(22)) cout << "number 22 is in the unordered_set " << endl;
        else cout << "22 is not in the unordered_set";
        
        return 0;
}

Output

unordered_set is not empty
size of the unordered_set is 5
maximum size of the unordered_set is 1152921504606846975
finding elemnt 12 in unordered_set
12
22 is not in the unordered_set

The post C++ STL Unordered Set – std::unordered_set appeared first on The Crazy Programmer.



from The Crazy Programmer https://www.thecrazyprogrammer.com/2017/10/stl-unordered-set.html

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan...

Rail Fence Cipher Program in C and C++[Encryption & Decryption]

Here you will get rail fence cipher program in C and C++ for encryption and decryption. It is a kind of transposition cipher which is also known as zigzag cipher. Below is an example. Here Key = 3. For encryption we write the message diagonally in zigzag form in a matrix having total rows = key and total columns = message length. Then read the matrix row wise horizontally to get encrypted message. Rail Fence Cipher Program in C #include<stdio.h> #include<string.h> void encryptMsg(char msg[], int key){ int msgLen = strlen(msg), i, j, k = -1, row = 0, col = 0; char railMatrix[key][msgLen]; for(i = 0; i < key; ++i) for(j = 0; j < msgLen; ++j) railMatrix[i][j] = '\n'; for(i = 0; i < msgLen; ++i){ railMatrix[row][col++] = msg[i]; if(row == 0 || row == key-1) k= k * (-1); row = row + k; } printf("\nEncrypted Message: "); for(i = 0; i < key; ++i) f...

Data Encryption Standard (DES) Algorithm

Data Encryption Standard is a symmetric-key algorithm for the encrypting the data. It comes under block cipher algorithm which follows Feistel structure. Here is the block diagram of Data Encryption Standard. Fig1: DES Algorithm Block Diagram [Image Source: Cryptography and Network Security Principles and Practices 4 th Ed by William Stallings] Explanation for above diagram: Each character of plain text converted into binary format. Every time we take 64 bits from that and give as input to DES algorithm, then it processed through 16 rounds and then converted to cipher text. Initial Permutation: 64 bit plain text goes under initial permutation and then given to round 1. Since initial permutation step receiving 64 bits, it contains an 1×64 matrix which contains numbers from 1 to 64 but in shuffled order. After that, we arrange our original 64 bit text in the order mentioned in that matrix. [You can see the matrix in below code] After initial permutation, 64 bit text passed throug...