The Wayback Machine - https://web.archive.org/web/20241001064328/https://www.geeksforgeeks.org/the-c-standard-template-library-stl/
Open In App

C++ Standard Template Library (STL)

Last Updated : 06 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorithms and containers.

STL was originally designed by Alexander Stepanov and was later accepted as the part of C++ standard in C++ 98. It is a generalized library so we can use it with almost every data type without repeating the implementation code.

Components of STL

The components of STL are the features provided by Standard Template Library (STL) in C++ that can be classified into 4 types:

  1. Containers
  2. Algorithms
  3. Iterators
  4. Functors

These components are designed to be efficient, flexible, and reusable, making them an integral part of modern C++ programming.

Containers

Containers are the data structures used to store objects and data according to the requirement. Each container is implemented as a template class that also contains the methods to perform basic operations on it. Every STL container is defined inside its own header file.

Containers can be further classified into 4 types:

  1. Sequence Containers
  2. Container Adaptors
  3. Associative Containers
  4. Unordered Associated Containers

Sequence Containers

Sequence containers store the data in the linear manner. They are also used to implement container adaptors.
There are 5 sequence containers in C++ STL:

  1. Arrays: The STL array is an implementation of a compile time non-resizable array. It contains various method for common array operations.
  2. Vector: An STL vector can be defined as the dynamic sized array which can be resized automatically when new elements are added or removed.
  3. Deque: Deque or Double-Ended Queue is sequence containers with the feature of expansion and contraction on both ends. It means we can add and remove the data to and from both ends.
  4. Lists: List container stores data in non-contiguous memory unlike vectors and only provide sequential access to the stored data. It basically implements the doubly linked list.
  5. Forward Lists: Forward lists also store the data in a sequential manner like lists, but with the difference that forward list stores the location of only the next elements in the sequence. It implements the singly linked list.

Container Adaptors

The container adapters are the type of STL containers that adapt existing container classes to suit specific needs or requirements.
There are 3 container adaptors in C++ STL:

  1. Stack: STL Stack follows the Last In First Out (LIFO) principle of element insertion and deletion. Also, these operations are performed only at one end of the stack.
  2. Queue: STL Queue follows the First In First Out (FIFO) principle, means the element are inserted first are removed first and the elements inserted last are removed at last. It uses deque container by default.
  3. Priority Queue: STL Priority Queue does not follow any of the FIFO or LIFO principle, but the deletion of elements is done on the basis of its priority. So, the element with the highest (by default) is always removed first. By default, it uses vector as underlying container.

Associative Containers

Associative containers are the type of containers that store the elements in a sorted order based on keys rather than their insertion order.
There are 4 associative containers in C++ STL:

  1. Sets: STL Set is a type of associative container in which each element has to be unique because the value of the element identifies it. By default, the values are stored in ascending order.
  2. Maps: STL Maps are associative containers that store elements in the form of a key-value pair. The keys have to be unique and the container is sorted on the basis of the values of the keys.
  3. Multisets: STL Multiset is similar to the set container except that it can store duplicate values.
  4. Multimaps: STL Multimap is similar to a map container but allows multiple mapped values to have same keys.

Unordered Associative Containers

Unordered associative containers store the data in no particular order, but they allow the fastest insertion, deletion and search operations among all the container types in STL.
There are 4 unordered associative containers in C++ STL:

  1. Unordered Set: STL Unordered Set stores the unique keys in the form of hash table. The order is randomized but insertion, deletion and search are fast.
  2. Unordered Multiset: STL Unordered Multiset works similarly to an unordered set but can store multiple copies of the same key.
  3. Unordered Map: STL Unordered Map stores the key-value pair in a hash table, where key is hashed to find the storage place.
  4. Unordered Multimap: STL Unordered Multimap container is similar to unordered map, but it allows multiple values mapped to the same key.

Algorithms

STL algorithms offer a wide range of functions to perform common operations on data (mainly containers). These functions implement the most efficient version of the algorithm for tasks such as sorting, searching, modifying and manipulating data in containers, etc. All STL algorithms are defined inside the <algorithm> and <numeric> header file.
There is no formal classification of STL algorithms, but we can group them into two types based on the type of operations they perform:

Manipulative Algorithms

Manipulative algorithms perform operations that modifies the elements of the given container or rearrange their order.
Some of the common manipulative algorithm includes:

  • copy: Copies a specific number of elements from one range to another.
  • fill: Assigns a specified value to all elements in a range.
  • transform: Applies a function to each element in a range and stores the result in another range.
  • replace: Replaces all occurrences of a specific value in a range with a new value.
  • swap: Exchanges the values of two variables.
  • reverse: Reverses the order of elements in a range.
  • rotate: Rotates the elements in a range such that a specific element becomes the first.
  • remove: Removes all elements with a specified value from a range but does not reduce the container size.
  • unique: Removes consecutive duplicate elements from a range.

Non-Manipulative Algorithms

Non-manipulating algorithms are the type of algorithms provided by the Standard Template Library (STL) that operate on elements in a range without altering their values or the order of the elements.
The below are the few examples of the STL’s non-manipulative algorithms:

  • max_element: Find the maximum element in the given range.
  • min_element : To find the minimum element in the given range.
  • accumulate: Finds the sum of the elements of the given range.
  • count: Counts the occurrences of given element in the range.
  • find: Returns an iterator to the first occurrence of an element in the range.
  • is_permutation: Checks if one range is a permutation of another.
  • is_sorted: Checks if the elements in a range are sorted in non-decreasing order.
  • partial_sum: Computes the cumulative sum of elements in a range.

Iterators

Iterators are the pointer like objects that are used to point to the memory addresses of STL containers. They are one of the most important components that contributes the most in connecting the STL algorithms with the containers. Iterators are defined inside the <iterator> header file.

In C++ STL, iterators are of 5 types:

  1. Input Iterators: Input Iterators can be used to read values from a sequence once and only move forward.
  2. Output Iterators: Output Iterators can be used to write values into a sequence once and only move forward.
  3. Forward Iterators: Forward Iterators combine the features of both input and output iterators.
  4. Bidirectional Iterators: Bidirectional Iterators support all operations of forward iterators and additionally can move backward.
  5. Random Access Iterators: Random Access Iterators support all operations of bidirectional iterators and additionally provide efficient random access to elements.

Functors

Functors are objects that can be treated as though they are a function. Functors are most commonly used along with STL algorithms. It overloads the function-call operator () and allows us to use an object like a function. There are many predefined functors in C++ STL that are defined inside the <functional> header file.

Functors can be classified into multiple types based on the type of operator they perform:

  1. Arithmetic Functors
  2. Relational Functors
  3. Logical Functors
  4. Bitwise Functors

Arithmetic Functors

  • plus – Returns the sum of two parameters.
  • minus – Returns the difference of two parameters.
  • multiplies – Returns the product of two parameters.
  • divides – Returns the result after dividing two parameters.
  • modulus – Returns the remainder after dividing two parameters.
  • negate – Returns the negated value of a parameter.

Relational Functors

  • equal_to – Returns true if the two parameters are equal.
  • not_equal_to – Returns true if the two parameters are not equal.
  • greater – Returns true if the first parameter is greater than the second.
  • greater_equal – Returns true if the first parameter is greater than or equal to the second.
  • less – Returns true if the first parameter is less than the second.
  • less_equal – Returns true if the first parameter is less than or equal to the second.

Logical Functors

  • logical_and – Returns the result of Logical AND operation of two parameters.
  • logical_or – Returns the result of Logical OR operation of two parameters.
  • logical_not – Returns the result of Logical NOT operation of the parameters.

Bitwise Functors

  • bit_and – Returns the result of Bitwise AND operation of two parameters.
  • bit_or – Returns the result of Bitwise OR operation of two parameters.
  • bit_xor – Returns the result of Bitwise XOR operation of two parameters.

Utility and Memory Library

The Utility Library is a collection of utility components provided by the Standard Template Library (STL) that does not fall in the above categories. It offers various features such as pairs, tuples, etc.

The memory library contains the function that helps users to efficiently manage the memory such as std::move, smart pointers, etc.

  1. Pair: Container to store and manipulate heterogeneous data.
  2. Move Semantics: It allows the transfer of resources from one object to another without copying.
  3. Smart Pointers: They are a wrapper over the raw pointers and helps in avoiding errors associated with pointers.
  4. Utility Functions: Utility functions in C++ provide important operations like std::forward to facilitate efficient , generic and safe code manipulation.
  5. Integer Sequence: Enable compile-time generation of integer sequences, useful in metaprogramming.

Benefits of C++ Standard Template Library (STL)

The key benefit of the STL is that it provides a way to write generic, reusable code and tested code that can be applied to different data types. This means you can write an algorithm once, and then use it with other types of data without having to write separate code for each type.
Other benefits include:

  • STL provides flexibility through customizable templates, functors, and lambdas.
  • Pre-implemented tools let you focus on problem-solving rather than low-level coding.
  • STL handles memory management which reduces common errors like memory leaks.

Limitations of C++ Standard Template Library (STL)

The major limitation of the C++ Standard Template Library (STL) is Performance Overheads. While STL is highly optimized for general use cases, its generic nature can lead to less efficient memory usage and execution time compared to custom and specialized solutions.
Other limitations can be:

  • Complexity of debugging.
  • Lack of control over memory management.
  • Limited support for concurrent programming.
  • Limited flexibility with custom data structures integrating.

Despite these limitations, STL remains an invaluable part of C++ programming, offering a wide range of powerful and flexible tools.



Similar Reads

Sort in C++ Standard Template Library (STL)
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By defa
6 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Binary Search in C++ Standard Template Library (STL)
Binary search is a widely used searching algorithm that requires the array to be sorted before search is applied. The main idea behind this algorithm is to keep dividing the array in half (divide and conquer) until the element is found, or all the elements are exhausted.It works by comparing the middle item of the array with our target, if it match
3 min read
Multimap in C++ Standard Template Library (STL)
Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap make it very much useful i
6 min read
Queue in C++ Standard Template Library (STL)
Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a specific set of member functions to access its eleme
3 min read
Deque in C++ Standard Template Library (STL)
Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed. Double Ended Queues are basically an implementation of the data structure doub
4 min read
Pair in C++ Standard Template Library (STL)
Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples. The pair container is a simple container defined in <utility> header consisting of two data elements or objects. The first element is referen
9 min read
List in C++ Standard Template Library (STL)
Lists are sequence containers that allow non-contiguous memory allocation. As compared to the vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick (constant time). Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward_list. std::
6 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is defined inside the <set> header file. Syntax: std:
7 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Containers in C++ STL (Standard Template Library)
A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference ob
2 min read
Multiset in C++ Standard Template Library (STL)
Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. Some Basic Functions associated with multiset: begin() - Returns an iterator to the first element in the multiset --> O(1)end() - Returns an iterator to the theoretical element that follows the last element in th
6 min read
Unordered Sets in C++ Standard Template Library
An unordered_set is an unordered associative container implemented using a hash table where keys are hashed into indices of a hash table so that the insertion is always randomized. All operations on the unordered_set take constant time O(1) on an average which can go up to linear time O(n) in the worst case which depends on the internally used hash
6 min read
Difference Between STL and Standard Library in C++
In C++, the term "Standard Library" and "Standard Template Library" are often misinterpreted as the same. Although they sound same with only a single word difference, they refer to the different part of the C++ programming language. In this article, we will learn what's the difference between the C++ Standard Library and Standard Template Library (
3 min read
Algorithm Library Functions in C++ STL
Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Find element in rangestd :: find_if_not : Find elemen
4 min read
<iterator> library in C++ STL
Iterators in C++ STL | Introduction Functions Iterator operations : std :: advance : Advance iteratorstd :: distance : Return distance between iteratorsstd :: begin : Iterator to beginningstd :: end : Iterator to endstd :: prev : Get iterator to previous elementstd :: next : Get iterator to next elementstd :: next vs std :: advanceAll functions in
1 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
<strings> library in C++ STL
Member functions String.constructor : Construct string object (public member function ).String.destructor : String destructor (public member function )String.operator= : String assignment (public member function ) Iterators Begin : Return iterator to beginning (public member function )End : Return iterator to end (public member function )Advance :
3 min read
<numeric> library in C++ STL
Common mathematical functions std::fabs: This function returns the absolute value. std::sqrt: This function returns the square root std::sin: This function returns the sine measured in radians. Special mathematical functions std::beta: This function evaluates the (complete) Beta integral with given parameters std::hermite: This function Returns the
2 min read
<regex> library in C++ STL
Main classes These classes encapsulate a regular expression and the results of matching a regular expression within a target sequence of characters. basic_regex: Regular expression object (class template) sub_match: Identifies the sequence of characters matched by a sub-expression (class template) match_results: Identifies one regular expression ma
2 min read
Opening Modes in Standard I/O in C/C++ with Examples
Pre-requisites: File Handling in C++ So far the operations using the C program are done on a prompt/terminal that is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be perfo
13 min read
C++ 03 Standard
The C++ programming language, initially developed by Bjarne Stroustrup in 1983, quickly became one of the most popular programming languages due to its efficiency, flexibility, and support for object-oriented programming. However, as the language evolved, variations and extensions introduced by different compiler vendors led to compatibility issues
4 min read
C++ 23 Standard
C++23, officially known as ISO/IEC 14882:2023, is the latest standardized version of the C++ programming language, published in 2023. As C++ introduces new improvements and features every 3 years in the form of a standard like C++20 introduced powerful features such as concepts, ranges, and coroutines, marking a substantial leap in expressiveness a
6 min read
Why are Standard Iterator Ranges [begin, end) Instead of [begin, end]?
In C++, the Standard Template Library (STL) uses a half-open range convention [begin, end) for iterator ranges. This means the range includes the begin iterator but excludes the end iterator. A common question arises: Why does the STL adopt this convention instead of the fully closed range [begin, end]? In this article, we will learn the advantages
4 min read
What are the Complexity Guarantees of the Standard Containers?
In C++, the Standard Template Library (STL) provides various containers such as std::vector, std::list, std::map, and others, each designed for specific use cases. A very important aspect when we choose the right container for our application is to understand the complexity guarantees they offer for various operations. These guarantees allow us to
3 min read
C++ 11 Standard
C++ 11, officially known as ISO/IEC 14882:2011, is a significant version of the C++ programming language standard, published in 2011. It marked a major fix up of the language, introducing various features and enhancements that improved the usability, performance, and safety of C++ code. Before C++ 11, C++ 03 was the standard, and while it solidifie
5 min read
C++ 98 Standard
C++ 98, officially known as ISO/IEC 14882:1998, was the first international standard for the C++ programming language, published in 1998. This version standardized features that were already widely used in the C++ community and also introduced some new features that laid the foundation for future advancements in the language. Before C++ 98, C++ was
4 min read
is_rvalue_reference Template in C++
The std::is_rvalue_reference template of C++ STL is used to check whether the type is a rvalue reference type or not. It returns a boolean value showing the same. Syntax: template <class T > struct is_rvalue_reference; Parameters: This template accepts a single parameter T (Trait class) to check whether T is a rvalue reference type. Return Va
2 min read
is_fundamental Template in C++
The is_fundamental template of C++ STL is used to check whether the type is a fundamental type or not. It returns a boolean value showing the same. Syntax: template <class T> struct is_fundamental; Parameter: This template accepts a single parameter T (Trait class) to check whether T is a fundamental type or not. Return Value: This template r
2 min read
is_pointer Template in C++
The std::is_pointer template of C++ STL is used to check whether the given type is pointer or not. It returns a boolean value showing the same. Syntax: template <class T > struct is_pointer; Parameter: This template accepts a single parameter T (Trait class) to check whether T is a pointer or not. Return Value: This template returns a boolean
2 min read
Article Tags :
Practice Tags :