STL
Explore the use of balanced binary search trees in the C++ Standard Template Library. Understand Set, Multiset, and Map containers, their operations, and how to iterate through them efficiently. Learn time complexities and practical usage to improve your competitive programming solutions.
We'll cover the following...
Library
As briefly mentioned before, there are 3 variants of Balanced BST in STL that we are particularly interested in:
Set
MultiSet
Map
Include statement:
#include <set>
#include <multiset>
#include <map>
Set
The Set is a container that stores unique elements following a specific order.
Below are the operations we’ll be using frequently. For complete documentation check here.
set<int> S; // empty setbool x = S.empty(); // to check if set is emptyint sz = S.size(); // get size of setS.insert(x); // Insert integer x into the setS.erase(x); // Remove integer x from the setS.erase(it); // Iterator version of eraseset<int>::iterator it = S.find(x); // Returns iterator to element with passed value if exists else return iterator to S.end()
Since a set only has unique elements, adding duplicate elements doesn’t have any effect.
Multiset
Multiset elevates the limitation with Set, we can have duplicate elements in a multiset.
Below are the operations we’ll be using frequently. For complete documentation check here.
multiset<int> S; // empty multisetbool x = S.empty(); // to check if multiset is emptyint sz = S.size(); // get size of multisetS.insert(x); // Insert integer x into the multisetS.erase(x); // Remove integer x from the multisetS.erase(it); // Iterator version of erasemultiset<int>::iterator it = S.find(x); // Returns iterator to element with passed value if exists else return iterator to S.end()
The Iterator version of
erase()should be used when dealing with multiset. The non-iterator version ...