STL Containers: Set in C++
Introduction
The Standard Template Library (STL) in C++ provides a collection of generic classes and functions, including several container types. One of the most commonly used containers is the set
. A set
is a type of associative container in which each element must be unique. Sets are typically implemented as binary search trees, which allows for efficient insertion, deletion, and lookup operations.
Creating a Set
To create a set in C++, you need to include the <set>
header file:
#include <set>
Here is an example of creating a set of integers:
#include <iostream>
#include <set>
int main() {
std::set<int> mySet;
mySet.insert(1);
mySet.insert(2);
mySet.insert(3);
for (int x : mySet) {
std::cout << x << " ";
}
return 0;
}
Basic Operations
Below are some of the basic operations that can be performed on a set:
insert(value)
- Inserts a value into the set.erase(value)
- Removes a value from the set.find(value)
- Searches for a value in the set and returns an iterator to it if found.size()
- Returns the number of elements in the set.clear()
- Removes all elements from the set.
Here is an example demonstrating these operations:
#include <iostream>
#include <set>
int main() {
std::set<int> mySet;
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
std::cout << "Set size: " << mySet.size() << std::endl;
mySet.erase(20);
std::cout << "Set size after erase: " << mySet.size() << std::endl;
if (mySet.find(10) != mySet.end()) {
std::cout << "Element 10 found in the set." << std::endl;
}
mySet.clear();
std::cout << "Set size after clear: " << mySet.size() << std::endl;
return 0;
}
Set size: 3
Set size after erase: 2
Element 10 found in the set.
Set size after clear: 0
Iterating Over a Set
You can iterate over the elements of a set using iterators or range-based for loops. Here is an example:
#include <iostream>
#include <set>
int main() {
std::set<int> mySet = {100, 200, 300};
// Using iterator
for (std::set<int>::iterator it = mySet.begin(); it != mySet.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// Using range-based for loop
for (int x : mySet) {
std::cout << x << " ";
}
return 0;
}
100 200 300
100 200 300
Custom Comparator
By default, the set
stores elements in ascending order. However, you can define a custom comparator to change the ordering. Here is an example of storing elements in descending order:
#include <iostream>
#include <set>
struct Descending {
bool operator()(const int &a, const int &b) const {
return a > b;
}
};
int main() {
std::set<int, Descending> mySet = {1, 2, 3, 4, 5};
for (int x : mySet) {
std::cout << x << " ";
}
return 0;
}
Conclusion
The set
container in C++ STL is a powerful tool for storing unique elements in a sorted manner. It provides efficient operations for insertion, deletion, and lookup. Understanding how to use sets and their various functionalities can greatly enhance your ability to manage collections of data in C++.