Introduction
Set is a data structure that only stores unique elements.
Types of Set
There are two types of set in cpp.
- Ordered Set - Maintain sorting while insertion
- 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
- Removing duplicates in an array
- Set Operations
Top comments (0)