Set
- std::set is an associative container that contains a sorted set of unique objects. It is usually implemented as a red-black tree.
Initialization
Insert Elements
- Insert Single Element (Average case O(log n)):
mySet.insert(10); // Insert an element
- Emplace Element (Average case O(log n)):
mySet.emplace(10); // Construct and insert element
Access Elements
- Find Element (Average case O(log n)):
auto it = mySet.find(10); // Returns iterator to the element if found, otherwise returns mySet.end()
Removing Elements
- Remove Element by Value (Average case O(log n)):
mySet.erase(10); // Erases element with value 10
Query Attributes
size_t size = mySet.size(); // Returns the number of elements
- Check if Set is Empty (O(1)):
bool isEmpty = mySet.empty(); // Returns true if set is empty, otherwise false
Iterating through Set
for (auto it = mySet.begin(); it != mySet.end(); ++it) {
// Access the element as *it
}
- Using Range-based For Loop (O(n)):
for (const auto& elem : mySet) {
// Access the element directly as elem
}
Other Common Operations
mySet.clear(); // Removes all elements from the set