Skip to content
Author: Tianle Yuan

Unordered Set⚓︎

This data structure is used for the case we DON'T need the key-value pairs like in the unordered_map. It is a easy way to implement presence/absence

Declaration
declaration.c++
std::unordered_set<int> Set;

Directory⚓︎

  • Insert elements: insert().
  • Count element presence time: count().
  • Check element existence: find.

insert()⚓︎

insert().c++
Set.insert(1);
Example

#include <iostream> #include <unordered_set> using namespace std; //declare an unordered set globally unordered_set Set = {2, -1}; int main() { //insert the element Set.insert(1); for (auto itr = Set.begin(); itr != Set.end(); itr++) { cout << (*itr) << endl; } }

count()⚓︎

count().c++
Set.count(2);
Details

Used to check if an element is present in the container or not. The function returns 1 if the element is present in the container; otherwise, it returns 0.

Equals to return (Set.find(<element>) != Set.end());. Same performance. See find().

Example

#include <iostream> #include <unordered_set> using namespace std; //declare an unordered set globally unordered_set Set = {2, -1, 1, 2}; int main() { cout << "2 exsists times: " << Set.count(2) << endl; cout << "All elements:" << endl; for (auto itr = Set.begin(); itr != Set.end(); itr++) { cout << (*itr) << " " << endl; } }

find()⚓︎

find().c++
Set.find(-1);
Example

#include <iostream> #include <unordered_set> using namespace std; //declare an unordered set globally unordered_set Set = {2, -1, 1, 2}; int main() { //Check result using find() cout << (Set.find(-1) != Set.end()) << endl; //Check result using count() cout << Set.count(-1) << endl; }

References⚓︎

Comments