Sets
Introduction to Sets in Standard Template Library
Sets are a type of associative container in the Standard Template Library (STL) of C++. They are mainly used to store unique elements following a specific order. In a set, the value of the element also identifies it (the value is itself the key, of type T), and each value must be unique.
How to Declare a Set
To declare a set, you can use the following syntax:
std::set<datatype> setname;
Here, datatype
could be any valid C++ data type and setname
is the name of the set.
For example:
std::set<int> mySet;
The above line declares a set of integers with the name mySet
.
Basic Operations
Sets in C++ STL provide several functions to perform different operations. Some of the basic ones include:
- insert(): This function is used to insert elements into the set.
mySet.insert(30); // inserts 30 into the set
- erase(): This function is used to remove elements from the set. It can erase elements by their value or by their position.
mySet.erase(30); // erases 30 from the set
- find(): This function returns an iterator to the element if it is found, otherwise it returns an iterator to
set::end
.
auto it = mySet.find(20); // finds 20 in the set
- size(): This function returns the number of elements present in the set.
int size = mySet.size(); // returns the size of the set
- empty(): This function returns true if the set is empty, otherwise false.
bool isEmpty = mySet.empty(); // checks if the set is empty
Set Iterators
Just like other STL containers, sets too have iterators. You can declare an iterator for a set as follows:
std::set<int>::iterator it;
You can iterate through the elements of a set using the iterator:
for (it = mySet.begin(); it != mySet.end(); it++)
{
std::cout << *it << " ";
}
Set Characteristics
Here are some key points to remember about sets:
- Sets are typically implemented as binary search trees.
- Insertion, removal, and search operations have logarithmic complexity.
- Sets do not allow for modification of its elements. This is because the modification could potentially violate the set's ordering property.
- If you need to change a value in a set, the correct approach is to remove the old value and insert the new one.
Conclusion
Sets in C++ STL are powerful tools that allow us to deal with a group of unique elements in a sorted manner. They provide a variety of built-in functions which makes it easy to implement and manipulate sets. However, keep in mind that the elements of a set are always sorted and unique, which makes it different from other containers such as vectors or lists.