The Standard Template Library (STL) is a
software library
In computer science, a library is a collection of non-volatile resources used by computer programs, often for software development. These may include configuration data, documentation, help data, message templates, pre-written code and sub ...
originally designed by
Alexander Stepanov
Alexander Alexandrovich Stepanov (russian: Алекса́ндр Алекса́ндрович Степа́нов; born November 16, 1950, Moscow) is a Russian-American computer programmer, best known as an advocate of generic programming and as th ...
for the
C++ programming language that influenced many parts of the
C++ Standard Library
The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. ISO/ IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C §7'' Starting from the original ANSI C standard, it wa ...
. It provides four components called ''
algorithm
In mathematics and computer science, an algorithm () is a finite sequence of rigorous instructions, typically used to solve a class of specific problems or to perform a computation. Algorithms are used as specifications for performing ...
s'', ''
containers
A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping.
Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
'', ''
functions'', and ''
iterator
In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface. Though the interface and semantics of a given ite ...
s''.
The STL provides a set of common
classes for C++, such as containers and
associative array
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an ...
s, 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
templates. This approach provides
compile-time polymorphism that is often more efficient than traditional
run-time polymorphism
In programming language theory and type theory, polymorphism is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types.: "Polymorphic types are types whose operation ...
. Modern C++
compiler
In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
s are tuned to minimize abstraction penalties arising from heavy use of the STL.
The STL was created as the first library of generic algorithms and data structures for C++, with four ideas in mind:
generic programming
Generic programming is a style of computer programming in which algorithms are written in terms of types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneered b ...
,
abstractness without loss of efficiency, the
Von Neumann computation model,
and
value semantics In computer science, having value semantics (also value-type semantics or copy-by-value semantics) means for an object that only its value counts, not its identity. Immutable objects have value semantics trivially, and in the presence of mutation, a ...
.
The STL and the
C++ Standard Library
The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. ISO/ IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C §7'' Starting from the original ANSI C standard, it wa ...
are two distinct entities.
History
In November 1993
Alexander Stepanov
Alexander Alexandrovich Stepanov (russian: Алекса́ндр Алекса́ндрович Степа́нов; born November 16, 1950, Moscow) is a Russian-American computer programmer, best known as an advocate of generic programming and as th ...
presented a library based on generic programming to the
ANSI/ISO committee for C++ standardization. The committee's response was overwhelmingly favorable and led to a request from
Andrew Koenig for a formal proposal in time for the March 1994 meeting. The committee had several requests for changes and extensions and the committee members met with Stepanov and Meng Lee to help work out the details. The requirements for the most significant extension (
associative container
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an ...
s) had to be shown to be consistent by fully implementing them, a task Stepanov delegated to
David Musser David "Dave" Musser is a professor emeritus of computer science at the Rensselaer Polytechnic Institute in Troy, New York, United States.
He is known for his work in generic programming, particularly as applied to C++, and his collaboration with ...
. A proposal received final approval at the July 1994 ANSI/ISO committee meeting. Subsequently, the Stepanov and Lee document 17 was incorporated into the ANSI/ISO C++ draft standard (1, parts of clauses 17 through 27).
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
The Internet (or internet) is the global system of interconnected computer networks that uses the Internet protocol suite (TCP/IP) to communicate between networks and devices. It is a ''internetworking, network of networks'' that consists ...
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
containers
A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping.
Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
and associative containers. The containers are objects that store data. The standard
sequence containers include , , and . The standard
associative containers
In computing, associative containers refer to a group of class templates in the standard library of the C++ programming language that implement ordered associative arrays. Being templates, they can be used to store arbitrary elements, such as ...
are , , , , , , and . There are also ''container adaptors'' , , and , that are containers with specific interface, using other containers as implementation.
Iterators
The STL implements five different types of
iterator
In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface. Though the interface and semantics of a given ite ...
s. 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 ''s'' (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.
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
deques. User-created
containers
A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping.
Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
only have to provide an iterator that implements one of the five standard iterator interfaces, and all the algorithms provided in the STL can be used on the container.
This generality also comes at a price at times. For example, performing a search on an
associative container
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an ...
such as a map or set can be much slower using iterators than by calling member functions offered by the container itself. This is because an associative container's methods can take advantage of knowledge of the internal structure, which is opaque to algorithms using iterators.
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 and use
binary search
In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the m ...
and like sorting algorithms require that the type of data must implement comparison operator or custom comparator function must be specified; such comparison operator or comparator function must guarantee
strict weak ordering
In mathematics, especially order theory, a weak ordering is a mathematical formalization of the intuitive notion of a ranking of a set, some of whose members may be tied with each other. Weak orders are a generalization of totally ordered ...
. Apart from these, algorithms are provided for making heap from a range of elements, generating lexicographically ordered permutations of a range of elements, merge sorted ranges and perform
union
Union commonly refers to:
* Trade union, an organization of workers
* Union (set theory), in mathematics, a fundamental operation on sets
Union may also refer to:
Arts and entertainment
Music
* Union (band), an American rock group
** ''Un ...
,
intersection
In mathematics, the intersection of two or more objects is another object consisting of everything that is contained in all of the objects simultaneously. For example, in Euclidean geometry, when two lines in a plane are not parallel, thei ...
,
difference of sorted ranges.
Functions
The STL includes classes that
overload the function call operator (). Instances of such classes are called functors or
function objects
In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax (a function parameter that can also be a function). Function objects are often ...
. Functors allow the behavior of the associated function to be parameterized (e.g. through arguments passed to the functor's
constructor
Constructor may refer to:
Science and technology
* Constructor (object-oriented programming), object-organizing method
* Constructors (Formula One), person or group who builds the chassis of a car in auto racing, especially Formula One
* Construc ...
) and can be used to keep associated per-functor state information along with the function. Since both functors and function pointers can be invoked using the syntax of a function call, they are interchangeable as arguments to templates when the corresponding parameter only appears in function call contexts.
A particularly common type of functor is the
predicate
Predicate or predication may refer to:
* Predicate (grammar), in linguistics
* Predication (philosophy)
* several closely related uses in mathematics and formal logic:
**Predicate (mathematical logic)
**Propositional function
**Finitary relation, ...
. For example, algorithms like take a
unary predicate that operates on the elements of a sequence. Algorithms like sort, partial_sort, nth_element and all sorted
containers
A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping.
Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
use a
binary
Binary may refer to:
Science and technology Mathematics
* Binary number, a representation of numbers using only two digits (0 and 1)
* Binary function, a function that takes two arguments
* Binary operation, a mathematical operation that ta ...
predicate that must provide a
strict weak ordering
In mathematics, especially order theory, a weak ordering is a mathematical formalization of the intuitive notion of a ranking of a set, some of whose members may be tied with each other. Weak orders are a generalization of totally ordered ...
, that is, it must behave like a
membership
Member may refer to:
* Military jury, referred to as "Members" in military jargon
* Element (mathematics), an object that belongs to a mathematical set
* In object-oriented programming, a member of a class
** Field (computer science), entries in ...
test on a transitive, non-reflexive and asymmetric
binary relation
In mathematics, a binary relation associates elements of one set, called the ''domain'', with elements of another set, called the ''codomain''. A binary relation over Set (mathematics), sets and is a new set of ordered pairs consisting of ele ...
. If none is supplied, these algorithms and containers us
lessby default, which in turn calls the less-than-operator <.
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
Pretty-printing (or prettyprinting) is the application of any of various stylistic formatting conventions to text files, such as source code, markup, and similar kinds of content. These formatting conventions may entail adhering to an indentatio ...
STL-related error messages to make them more comprehensible.
* Careless use of templates can lead to
code bloat
In computer programming, code bloat is the production of program code (source code or machine code) that is perceived as unnecessarily long, slow, or otherwise wasteful of resources. Code bloat can be caused by inadequacies in the programming lang ...
. 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
A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping.
Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
with constants within the source code is not as easy as data structures inherited from C (addressed in
C++11
C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versio ...
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.
* The
concept
Concepts are defined as abstract ideas. They are understood to be the fundamental building blocks of the concept behind principles, thoughts and beliefs.
They play an important role in all aspects of cognition. As such, concepts are studied by s ...
of iterators as implemented by the STL can be difficult to understand at first: for example, if a value pointed to by the iterator is deleted, the iterator itself is then no longer valid. This is a common source of errors. Most implementations of the STL provide a debug mode that is slower, but can locate such errors if used. A similar problem exists in other languages, for example
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
.
Ranges
In the Hebrew Bible and in the Old Testament, the word ranges has two very different meanings.
Leviticus
In Leviticus 11:35, ranges probably means a cooking furnace for two or more pots, as the Hebrew word here is in the dual number; or perhaps ...
have been proposed as a safer, more flexible alternative to iterators.
* Certain iteration patterns do not map to the STL iterator model. For example, callback enumeration APIs cannot be made to fit the STL model without the use of
coroutine
Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative ...
s, which are platform-dependent or unavailable, and will be outside the C++ standard until C++20.
* Compiler compliance does not guarantee that
Allocator objects, used for memory management for
containers
A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping.
Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
, will work with state-dependent behavior. For example, a portable library can't 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
C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versio ...
).
* The set of algorithms is not complete: for example, the algorithm was left out, though it has been added in
C++11
C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versio ...
.
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
Silicon Graphics, Inc. (stylized as SiliconGraphics before 1999, later rebranded SGI, historically known as Silicon Graphics Computer Systems or SGCS) was an American high-performance computing manufacturer, producing computer hardware and soft ...
. No longer maintained.
***
STLPort, based on SGI STL
***
Rogue Wave Standard Library (HP, SGI,
SunSoft
, stylized as SUNSOFT, is a Japanese video game developer and publisher.
Sunsoft is the video games division of Japanese electronics manufacturer Sun Corporation. Its U.S. subsidiary operated under the name Sun Corporation of America, though, ...
,
Siemens-Nixdorf)
**
Apache C++ Standard Library(The starting point for this library was the 2005 version of the Rogue Wave standard library
Apache C++ Standard Library
Stdcxx.apache.org. Retrieved on 2013-07-29.)
* Dinkum STL library by P.J. Plauger
Phillip James (P.J. or Bill) Plauger (; born January 13, 1944, Petersburg, West Virginia) is an author, entrepreneur and computer programmer. He has written and co-written articles and books about programming style, software tools, and the C p ...
* Th
Microsoft STL
which ships with Visual C++ is a licensed derivative of Dinkum's STL
Source is available on Github
developed by Paul Pedriana at Electronic Arts and published as part o
EA Open Source
See also
* List of C++ template libraries
The following list of C++ template libraries details the various libraries of templates available for the C++ programming language.
The choice of a typical library depends on a diverse range of requirements such as: desired features (e.g.: large ...
* C++11
C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versio ...
* Boost C++ Libraries
Boost is a set of libraries for the C++ programming language that provides support for tasks and structures such as linear algebra, pseudorandom number generation, multithreading, image processing, regular expressions, and unit testing. It conta ...
Notes
References
* Alexander Stepanov
Alexander Alexandrovich Stepanov (russian: Алекса́ндр Алекса́ндрович Степа́нов; born November 16, 1950, Moscow) is a Russian-American computer programmer, best known as an advocate of generic programming and as th ...
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.)
* Stepanov reflects about the design of the STL.
*
*
*
*
*
External links
C++ reference
C++ STL reference
includes C++11 features
STL programmer's guide
from SGI. Originally a
(retired content).
Apache (formerly Rogue Wave) C++ Standard Library Class Reference
Bjarne Stroustrup on The emergence of the STL
(Page 5, Section 3.1)
C++ Standard Specification
{{C++ programming language
C++ Standard Library
Generic programming