Open In App

Why does the C++ STL not provide any “tree” containers?

Improve
Improve
Like Article
Like
Save
Share
Report

What is STL in C++?

The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions. It is a library of container classes, algorithms, functions and iterators. 

It is a generalized library and so, its components are parameterized. Working knowledge of template classes is a prerequisite for working with STL. STL has 4 components:

  • Algorithms
  • Containers
  • Functions
  • Iterators

Containers: Containers are Objects that handle the collection of other objects or elements sequentially or hierarchically implementing well-defined data structures  

Examples: vector, set, queue, stack, list, map, etc.

 

Note: Checkout this article to know more about STL and Containers

Why STL does not have a “tree” container:

First, we should be looking at what is the need for a tree: 

  • Users want to store data in a hierarchical way or 
  • The user wants the data in a particular order. 

For both of these cases we already have containers 

set, multiset, and unordered_set: 

  • Set & multiset store the elements in an ordered manner, both are dynamic containers.  Set and multiset are internally built using the concept of the binary search tree. It inserts and removes data elements in O(log N ) time and it doesn’t store duplicate values. 
  • If you want to store duplicate values you can use multiset and if you don’t want them in any particular order you can use unordered_set that inserts and removes data elements in O(1) time.

Basically, the characteristics of these two containers are such that they practically have to be implemented using trees (though this is not actually a requirement).

map, multimap, and unordered_map: 

  • Dynamic containers like map, multimap, and unordered_map store data as a key-value pair. If the key has to be unique you can use map or unordered_map and 
  • In a multimap, multiple elements can have the same keys. The key-value pair can be used to store a parent and child relationship. 

One of the biggest advantages of these containers is they are generic classes so they can be customized. unordered_map stores data in a random order in O(1) time, and map and multimap store data in an ordered manner in O(log N) time.

Now according to our needs, we can use any of these containers to have the same characteristics as that of a tree.

Related Articles:


Last Updated : 05 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads