Logo

dev-resources.site

for different kinds of informations.

Set STL in CPP πŸ‘¨β€πŸŽ“

Published at
11/22/2024
Categories
cpp
stl
datastructures
algorithms
Author
aryan015
Categories
4 categories in total
cpp
open
stl
open
datastructures
open
algorithms
open
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);
}

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;
}

Erase an element

iSet.erase(20);
uSet.erase(20);

Iterate over an element

Iteration is same in ordered and Unordered Set

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

Get the size

std::cout << "Size: " << iSet.size() << std::endl;
std::cout << "Unordered Size: " << uSet.size() << std::endl;

Clear the set

iSet.clear();

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

Featured ones: