STL

C++ Standard Template Library

Overview

  • The Standard Template Library (STL) is one of the most important features added to C++ in recent years.
  • STL provides general-purpose, templatized classes and functions that implement algorithms and data structures.
  • Although the syntax of STL can be intimidating, it is actually quite easy to use once an understanting of hos it is constructed is known.
  • At the core of the STL are three foundational items:
    • Containers
    • Algorithms
    • Iterators
  • These items work in conjuction with one another to provide off-the-shelf solutions to a variety of programming problems.

Containers

  • Container are objects that hold other objects.
  • Container can be sequence containers such as vector class, deque and list. A sequence is a linear list.
  • Associative containers allow efficient retrieval of values based on keys. A map is an associative container as it provides access to values with unique keys.
  • Each container class defines a set of functions that may be applied to the container.
  • Container classes include vector, list, deque, set, multiset, map, multimap, hash set, hash multiset, hash map and hash_multimap.
  • They may also include other containers that are implementation dependen/extension.

Algorithms

  • Algorithms are used to process the elements of colelctions. For example, algorithms can search, sort and modify.
  • The data and operations in STL are decoupled. Container classes manage the data, and the operations are defined by the algorithms.
  • Algorithms operate on a range of elements within a container.

Iterators

  • Iterator is apointer used to manipulate the elements of the collections of objects. These collections may be containers or subsets of containers.
  • Iterators provide the ability to cycle through the contents of a container in much the same way as pointers are used to cycle through the contents of a container in much the same way as pointers are used to cycle through an array.
  • Every container class provides its own iterator type.
  • Iterator is a smart pointer. For example, to increment an iterator you call operator ++. To access the value of an iterator you may use operator *.
  • There are five types of iterators:

Types of Iterators

  • Conceptually, iterators are the linker between these two components. They let any algorithm interact with any container, graphically shown below.
  • Theoretically also, you can combine every kind of container with every kind of algorithm.

Relationship between Iterators, Containers and Algorithms

  • Relationship between the three STL components

Relationship between the STL components

Container Classes

Container Classes