Standard Template Library
C++ Standard Library |
---|
Containers |
C standard library |
The Standard Template Library (STL) is a
The STL provides a set of common classes for C++, such as containers and associative arrays, that can be used with any built-in type and with any user-defined type that supports some elementary operations (such as copying and assignment). STL algorithms are independent of containers, which significantly reduces the complexity of the library.
The STL achieves its results through the use of
The STL was created as the first library of generic algorithms and data structures for C++, with four ideas in mind: generic programming, abstractness without loss of efficiency, the Von Neumann computation model,[2] and value semantics.
The STL and the C++ Standard Library are two distinct entities.[3]
History
In November 1993
The prospects for early widespread dissemination of the STL were considerably improved with Hewlett-Packard's decision to make its implementation freely available on the Internet in August 1994. This implementation, developed by Stepanov, Lee, and Musser during the standardization process, became the basis of many implementations offered by compiler and library vendors today.
Composition
Containers
The STL contains sequence
areset
, multiset
, map
, multimap
, hash_set
, hash_map
, hash_multiset
and hash_multimap
. There are also container adaptors queue
, priority_queue
, and stack
, that are containers with specific interface, using other containers as implementation.
Container | Description |
---|---|
Simple containers | |
pair | The pair container is a simple associative container consisting of a 2-tuple of data elements or objects, called 'first' and 'second', in that fixed order. The STL 'pair' can be assigned, copied and compared. The array of objects allocated in a map or hash_map (described below) are of type 'pair' by default, where all the 'first' elements act as the unique keys, each associated with their 'second' value objects. |
Sequences (arrays/linked lists ): ordered collections
| |
vector
|
a amortized constant time . Removing the last element takes only constant time, because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time.
A specialization for type bool exists, which optimizes for space by storing bool values as bits. |
list | a doubly linked list; elements are not stored in contiguous memory. Opposite performance from a vector. Slow lookup and access (linear time), but once a position has been found, quick insertion and deletion (constant time). |
slist |
a singly linked list; elements are not stored in contiguous memory. Opposite performance from a vector. Slow lookup and access (linear time), but once a position has been found, quick insertion and deletion (constant time). It has slightly more efficient insertion and deletion, and uses less memory than a doubly linked list, but can only be iterated forwards. It is implemented in the C++ standard library as forward_list .
|
queue )
|
a vector with insertion/erase at the beginning or end in amortized constant time , however lacking some guarantees on iterator validity after altering the deque.
|
Container adaptors | |
queue
|
Provides queue interface in terms of push /pop /front /back operations.
Any sequence supporting operations |
priority queue | Provides priority queue interface in terms of push/pop/top operations (the element with the highest priority is on top).
Any random-access sequence supporting operations .
front() , push_back() , and pop_back() can be used to instantiate priority_queue (e.g. vector and deque ). It is implemented using a heapElements should additionally support comparison (to determine which element has a higher priority and should be popped first). |
stack
|
Provides stack interface in terms of push/pop/top operations (the last-inserted element is on top).
Any sequence supporting operations |
Associative containers: unordered collections | |
set
|
a mathematical strict weak ordering, otherwise behavior is undefined. Typically implemented using a self-balancing binary search tree .
|
multiset | same as a set, but allows duplicate elements (mathematical multiset). |
map
|
an strict weak ordering , otherwise behavior is undefined. Typically implemented using a self-balancing binary search tree.
|
multimap | same as a map, but allows duplicate keys. |
hash_set hash_multiset hash_map hash_multimap |
similar to a set, multiset, map, or multimap, respectively, but implemented using a hash table; keys are not ordered, but a hash function must exist for the key type. These types were left out of the C++ standard; similar containers were standardized in C++11, but with different names (unordered_set and unordered_map ).
|
Other types of containers | |
bitset | stores series of bits similar to a fixed-sized vector of bools. Implements bitwise operations and lacks iterators. Not a sequence. Provides random access. |
valarray | Another array data type, intended for numerical use (especially to represent vectors and matrices); the C++ standard allows specific optimizations for this intended purpose. According to Josuttis, valarray was badly designed, by people "who left the [C++ standard] committee a long time before the standard was finished", and expression template libraries are to be preferred.[4] A proposed rewrite of the valarray part of the standard in this vein was rejected, instead becoming a permission to implement it using expression template.[5]
|
Iterators
The STL implements five different types of iterators. These are input iterators (that can only be used to read a sequence of values), output iterators (that can only be used to write a sequence of values), forward iterators (that can be read, written to, and move forward), bidirectional iterators (that are like forward iterators, but can also move backwards) and random-access iterators (that can move freely any number of steps in one operation).
A fundamental STL concept is a range which is a pair of iterators that designate the beginning and end of the computation, and most of the library's algorithmic templates that operate on data structures have interfaces that use ranges.[6]
It is possible to have bidirectional iterators act like random-access iterators, so moving forward ten steps could be done by simply moving forward a step at a time a total of ten times. However, having distinct random-access iterators offers efficiency advantages. For example, a vector would have a random-access iterator, but a list only a bidirectional iterator.
Iterators are the major feature that allow the generality of the STL. For example, an algorithm to reverse a sequence can be implemented using bidirectional iterators, and then the same implementation can be used on lists, vectors and
This generality also comes at a price at times. For example, performing a search on an
Algorithms
A large number of algorithms to perform activities such as searching and sorting are provided in the STL, each implemented to require a certain level of iterator (and therefore will work on any container that provides an interface by iterators). Searching algorithms like binary_search
and lower_bound
use
Functors
The STL includes classes that
A particularly common type of functor is the
Criticisms
Quality of implementation of C++ compilers
The Quality of Implementation (QoI) of the C++ compiler has a large impact on usability of the STL (and templated code in general):
- Error messages involving templates tend to be very long and difficult to decipher. This problem has been considered so severe that a number of tools have been written that simplify and prettyprint STL-related error messages to make them more comprehensible.
- Careless use of templates can lead to code bloat.[7] This has been countered with special techniques within STL implementations (e.g. using void* containers internally and other "diet template" techniques) and improving compilers' optimization techniques. However, this symptom is similar to naively manually copying a set of functions to work with a different type, in that both can be avoided with care and good technique.
- Template instantiation can increase compilation time and memory usage, in exchange for typically reducing runtime decision-making (e.g. via virtual functions). Until the compiler technology improves enough, this problem can be only partially eliminated by careful coding, avoiding certain idioms, and simply not using templates where they are not appropriate or where compile-time performance is prioritized.
Other issues
- Initialization of STL containers with constants within the source code is not as easy as data structures inherited from C (addressed in C++11 with initializer lists).
- STL containers are not intended to be used as base classes (their destructors are deliberately non-virtual); deriving from a container is a common mistake.[8][9]
- The Ranges have been proposed as a safer, more flexible alternative to iterators.[10]
- Certain iteration patterns such as callback enumeration APIs cannot be made to fit the STL model without the use of coroutines,[11] which were outside the C++ standard until C++20.
- Compiler compliance does not guarantee that containers, will work with state-dependent behavior. For example, a portable library can not define an allocator type that will pull memory from different pools using different allocator objects of that type. (Meyers, p. 50) (addressed in C++11).
- The set of algorithms is not complete: for example, the
copy_if
algorithm was left out,[12] though it has been added in C++11.[13]
Implementations
- Original STL implementation by Stepanov and Lee. 1994, Hewlett-Packard. No longer maintained.
- SGI STL, based on original implementation by Stepanov & Lee. 1997, Silicon Graphics. No longer maintained.
- STLPort, based on SGI STL
- Siemens-Nixdorf)
- Apache C++ Standard Library (The starting point for this library was the 2005 version of the Rogue Wave standard library[14])
- Libstdc++ uses code derived from SGI STL for the algorithms and containers defined in C++03.
- SGI STL, based on original implementation by Stepanov & Lee. 1997, Silicon Graphics. No longer maintained.
- Dinkum STL library by P.J. Plauger
- The Microsoft STL which ships with Visual C++ is a licensed derivative of Dinkum's STL. Source is available on Github.
- EASTL, developed by Paul Pedriana at Electronic Arts and published as part of EA Open Source.
See also
- List of C++ template libraries
- C++11
- Boost C++ Libraries
Notes
- ISBN 1-57610-777-9.
The STL is made up of containers, iterators, function objects, and algorithms
- ISBN 0-201-37923-6.
- ^ Lightness Races in Orbit (5 March 2011). "What's the difference between "STL" and "C++ Standard Library"?". Stack Overflow. Retrieved 21 October 2021.
- ISBN 9780201379266.
- ISBN 0-201-73484-2.
- ^ Stepanov, Alexander; Lee, Meng (31 October 1995). "The Standard Template Library" (PDF). Retrieved 16 December 2018.
Most of the library's algorithmic templates that operate on data structures have interfaces that use ranges. A range is a pair of iterators that designate the beginning and end of the computation. [...] in general, a range [i, j) refers to the elements in the data structure starting with the one pointed to by i and up to but not including the one pointed to by j. Range [i, j) is valid if and only if j is reachable from i.
- ^ Adrian Stone. "Minimizing Code Bloat: Template Overspecialization".
- ISBN 0-321-33487-6.
- ISBN 0-321-11358-6.
- ^ Andrei Alexandrescu (6 May 2009). "Iterators Must Go" (PDF). BoostCon 2009. Retrieved 19 March 2011.
- ^ Matthew Wilson (February 2004). "Callback Enumeration APIs & the Input Iterator Concept". Dr. Dobb's Journal.
- ISBN 0-201-70073-5.: p.530
- ^ More STL algorithms (revision 2)
- ^ "Apache C++ Standard Library". stdcxx.apache.org. Retrieved 1 March 2023.
References
- Alexander Stepanov and Meng Lee, The Standard Template Library. HP Laboratories Technical Report 95-11(R.1), 14 November 1995. (Revised version of A. A. Stepanov and M. Lee: The Standard Template Library, Technical Report X3J16/94-0095, WG21/N0482, ISO Programming Language C++ Project, May 1994.)
- Alexander Stepanov (2007). Notes on Programming (PDF). Stepanov reflects about the design of the STL.
- ISBN 0-201-37926-0.
- ISBN 0-201-74962-9.
- Al Stevens (March 1995). "Al Stevens Interviews Alex Stepanov". Dr. Dobb's Journal. Retrieved 18 July 2007.
- ISBN 0-201-73484-2.
- ISBN 0-201-63398-1.
External links
- C++ reference
- C++ STL reference, includes C++11 features
- STL programmer's guide from SGI. Originally at [1] (retired content).
- Apache (formerly Rogue Wave) C++ Standard Library Class Reference
- Apache (formerly Rogue Wave) C++ Standard Library User Guide
- Bjarne Stroustrup on The emergence of the STL (Page 5, Section 3.1)
- C++ Standard Specification