STL in C++ is Standard Template Library which is powerful, adaptable, reusable generic classes and functions.

  • Powerful: Take an example as Vector vs Array. Clearly Vector (STL) is more powerful than normal array in C++.
  • Reusable: STL can hold or work with any type of primitive or user defined types.
  • Adaptable: It provides containers iterators and algorithms that we can adapt to do whatever we need to make them do.

STLs are basically containers which have fixed time and size complexity and usually are type-safe, extensible, consistent and fast.

Types of STL in C++

C++ STL has 3 important components:

Containers

Containers in STL is something which can hold values/data. In short, collections of objects or primitive datatypes. E.g array, vector, deque, map, stack etc.

Types of Containers

  • Sequence containers are the containers that maintain the ordering of the data stored in it. E.g array, vector, list, deque etc.
  • Associative containers stores data in predefined order or no order at all. E.g set, map etc
  • Container adapters are the variations of other containers. It does not support iterators thus cannot be used with algorithms. E.g stack, queue etc.

Algorithms

Algorithms in STL are functions for processing sequences of elements from containers. In short, they are used on containers for accomplishing some task or output. E.g find, max, count, sort etc.

Iterators

Iterators in STL generates sequences of elements from containers that algorithm uses. In short, they help in iterating through the elements of the containers. E.g forward, reverse, by value, by reference etc.

Types of Iterators

  • Input Iterators makes container element available to the program.
  • Output Iterators itearate over a sequence and write it into the conatiner.
  • Forward Iterators navigate one item at a time in one direction.
  • Bi-directional Iterators navigate one item at a time both directions.
  • Random Access Iterators uses subscript opeartor to directly access container element.

All the three components of STL are independent of each other yet they work with each other efficiently.

We will discuss each component of STL separately in depth but for now, let’s see a simple example to get a clear understanding of all the STL forms.

Output

sorted int stl vector output

This is just an overview of STL in C++. Each subtopic deserves separate self-discussion. Comment your suggestion or doubts.

Leave a Reply

Close Menu