Skip to main content

C++ STL Set Container – std::set

In this tutorial you will learn about STL Set container in C++ i.e. std::set and all functions applicable on it.

Set is a associative container. We know that in associative containers each element is unique. So sets are also containers that stores unique elements following in a specific order. The word associative means each value associated with a key value. For any kind of operation key will be more preferred than actual value. Here sets are special type of associative containers where value itself is key value.

Some more facts about set are, elements in set are constant. It means that we are unable to modify once we insert the element. If we want to update element then we should delete that element and again insert with updated element. The elements in the set are always sorted.

C++ STL Set

Let see some functions associated with sets:

Before working with functions let see iterators that can apply on list to manipulate the data in list.

begin(): returns iterator to the beginning

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

rbegin(): returns reverse iterator to reverse beginning

rend(): returns reverse iterator to reverse end.

These iterators we can use in our programs.

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

Inserting element into set:

There are different ways we can insert elements into set.

Note: In any method below when we insert an element into set it automatically inserted at proper position based on ascending sorted order.

Method 1: Insert directly by passing element.  setName.insert(element);

Method 2: Using iterator. This returns iterator at inserted position. setName.insert (iterator,value)

Method 3: Copying from another container.

Example program for inserting into set:

#include<iostream>
#include<set>

using namespace std;

int main(){
        set<int> s1; // declaring a set
        set<int> :: iterator it; // iterator for set
        
        for(int i=0;i<5;i++){
                s1.insert(i*10); // inserting using Method1
        }
        
        it= s1.begin();
        s1.insert(it,99); // inserting using Method2
        
        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 set
        
        return 0;
}

Output

0 10 20 23 30 34 40 45 56 99

Some more functions applicable on set are:

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

swap(): swaps elements of set1 to set2 and set2 to set1.

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

Example program to show usage of above functions:

#include<iostream>
#include<set>

using namespace std;

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

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

        s1.clear(); // clearing list1
        s1.empty() ? cout <<"list is empty" << endl: cout << "list is not empty" << endl;
        // ternary operation which resutls list is empty or not

        return 0;
}

Output

deleting element 12 –> 10 11 13 14
set1 elements before swapping –> 10 11 13 14
set2 elements before swapping –> 0 1 2 3
set1 elements after swapping –> 0 1 2 3
set2 elements after swapping –> 10 11 13 14
list is empty 

Some more functions are:

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

size(): returns the size of the list.

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

find(): It returns iterator to the element.

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

Example program to show usage of above functions:

#include<iostream>
#include<set>

using namespace std;

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

Output

list is not empty
size of the list is 5
maximum size of the list is 461168601842738790
finding elemnt 12 in list
12
22 is not in the list

Comment below if you have any queries or found any information incorrect in above tutorial for STL Set container in C++.

The post C++ STL Set Container – std::set appeared first on The Crazy Programmer.



from The Crazy Programmer http://www.thecrazyprogrammer.com/2017/08/stl-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...