Sets in C++ made easy

This tutorial will helps you in learning about Sets in C++. I have written in the simplest possible way. Like Maps, sets are also a type of associate containers which stores unique elements. The element value in the set is the key itself.

Set

Sets are associative containers that stores unique elements. All elements are ordered in set in C++.

Use
Sets are mainly used whenever we want to store unique items of a group or activities relating to unique elements. Eg - Program to print unique words from a file.

Defining a Set

Sets in java are defined as follows: -

set<string> set1;

Instead of string, we can use int, float and other data types.

Adding an entry to a Set

Entry/ Values can be added to set in the following ways: -

set1. insert("Sujith");

Checking whether a value is present in the Set

Entry/ Values can be checked in the Set for their presence. It is similar to those in Map. We use count for checking whether a value is there or not. The entries/ values are case sensitive.

bool check;
if(set1. count("Sujith"))
{
check = true;
}

Traversing a Set

Sets can be traversed with the help of a set iterator. Following represents how to traverse a set.

set1<int>::const_iterator iter;
for(iter = set1.begin(); iter != set1.end(); ++iter)
{
cout<<*iter<<endl;
}

Sample program in C++ to demonstrate the use of Sets

Program to print unique elements in an array.


#include<iostream>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<stdio.h>
#include<map>
#include<set>
#include<utility>
#include<vector>
#include <string>

using namespace std;
set<int> UniqueElements(vector<int> temp);

int main()
{
    vector<int> temp;
    int array[25]={1,2,3,4,1,2,35,6,7,3,7,8,8,9,10,12,11,1,1,4,5,3,2,1,6};
    
    for(int i=0;i<25;i++)
    {
        temp.push_back(array[i]);
    }
    set<int> uniqueItems = UniqueElements(temp);
    cout<<"The unique items in the array is as follows = "<<endl;
    set<int>::const_iterator pos;
    for(pos = uniqueItems.begin(); pos != uniqueItems.end(); ++pos)
    {
        cout<<*pos<<endl;
       
    }

    return 0;
}

set<int> UniqueElements(vector<int> temp)
{
    set<int> unique;
    for(int i=0;i<temp.size();i++)
    {
        
        unique.insert(temp[i]);
        
    }
    
    return unique;
    
}


Output of the program

Output of the above program is as follows: -

The unique items in the array is as follows =
1
2
3
4
5
6
7
8
9
10
11
12
35


I hope, this post have given you a good idea about Sets. Please comment below if you have any doubts.  Every doubt will be responded within a day. Suggestions are most welcome.

Similar posts

1) Map and sets in Java made easy - sujithforu.blogspot.com/2012/11/map-and-set-in-java-in-made-easy.html
2) Map in C++



Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++