160 views
C++ Set
The C++ std::set
is a container class provided by the Standard Template Library (STL) that represents a sorted set of unique elements. It is part of the C++ Standard Library and is implemented as a self-balancing binary search tree, typically a Red-Black Tree. Here are some key characteristics and operations of std::set
:
- Uniqueness: Elements in a
std::set
are unique, meaning that you cannot have duplicate elements. If you attempt to insert a duplicate element, it won’t be added. - Sorting: The elements in a
std::set
are automatically sorted in ascending order according to their values. You cannot change the order of elements in astd::set
. - Balanced Tree:
std::set
uses a self-balancing binary search tree as its underlying data structure. This ensures efficient insertion, deletion, and search operations, all of which have a logarithmic time complexity. - Iterators: You can use iterators to traverse the elements of a
std::set
in sorted order. Thebegin()
iterator points to the first element, and theend()
iterator points just beyond the last element. - Insertion and Deletion:
- To insert an element, you can use the
insert()
member function. - To remove an element, you can use the
erase()
member function. You can specify either an iterator to the element or the value of the element to be removed.
- Searching: You can search for elements in a
std::set
using thefind()
member function, which returns an iterator pointing to the found element orend()
if the element is not present. - Size: You can determine the number of elements in a
std::set
using thesize()
member function. - Empty Check: You can check if a
std::set
is empty using theempty()
member function.
Here’s an example of how to use std::set
:
C++
#include <iostream>
#include <set>
int main() {
std::set<int> mySet;
// Insert elements
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
// Duplicate values are ignored
mySet.insert(20);
// Iterate through the set
for (const int& value : mySet) {
std::cout << value << " ";
}
std::cout << std::endl;
// Erase an element
mySet.erase(20);
// Search for an element
std::set<int>::iterator it = mySet.find(10);
if (it != mySet.end()) {
std::cout << "Found: " << *it << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
In this example, a std::set
is used to store a collection of integers. The elements are automatically sorted, and duplicates are ignored. You can see how to insert, erase, and search for elements in the set.
std::set
is a useful container when you need a sorted collection of unique elements, and it provides efficient access and manipulation operations.