DEV Community

Cover image for Set STL in CPP ๐Ÿ‘จโ€๐ŸŽ“
aryan015
aryan015

Posted on

Set STL in CPP ๐Ÿ‘จโ€๐ŸŽ“

Introduction

Set is a data structure that only stores unique elements.

Types of Set

There are two types of set in cpp.

  1. Ordered Set - Maintain sorting while insertion
  2. Unordered Set - Insert in random order which makes it fast.

Initialize

#include <set>
using namespace std;
int main(){
    set<int> iSet;
    unordered_set<int> uSet;
    iSet.insert(10);
    uSet.insert(10);
}
Enter fullscreen mode Exit fullscreen mode

Check for an element

if (iSet.find(20) != iSet.end()) {
    cout << "20 is in the set" << endl;
}
if (uSet.find(20) != uSet.end()) {
    cout << "20 is in the set" << endl;
}
Enter fullscreen mode Exit fullscreen mode

Erase an element

iSet.erase(20);
uSet.erase(20);
Enter fullscreen mode Exit fullscreen mode

Iterate over an element

Iteration is same in ordered and Unordered Set

for (auto it = iSet.begin(); it != iSet.end(); ++it) {
    std::cout << *it << " ";
}
Enter fullscreen mode Exit fullscreen mode

Get the size

std::cout << "Size: " << iSet.size() << std::endl;
std::cout << "Unordered Size: " << uSet.size() << std::endl;
Enter fullscreen mode Exit fullscreen mode

Clear the set

iSet.clear();
Enter fullscreen mode Exit fullscreen mode

Difference Between Ordered and Unordered set

Feature std::set std::unordered_set
Order Stores elements in sorted order No particular order
Time Complexity O(log n) for insert, delete, search O(1) average for insert, delete, search
Duplicates Not allowed Not allowed
Use Case When sorting is needed When fast operations are needed

Application

  1. Removing duplicates in an array
  2. Set Operations

Top comments (0)