Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Standard Template Library

From Wikipedia, the free encyclopedia
Software library for the C++ programming language
Not to be confused withC++ Standard Library.
For other uses, seeSTL.

C++ Standard Library
Containers
C standard library
This article is part ofa series on the
C++ programming language
The logo of the C++ programming language

TheStandard Template Library (STL) was asoftware library originally designed byAlexander Stepanov for theC++ programming language that influenced many parts of theC++ Standard Library, though no longer is actively maintained and is now mostly integrated into the C++ standard library itself. It provides four components calledalgorithms,containers,functors, anditerators.[1]

The STL provides a set of commonclasses for C++, such as containers andassociative arrays, that can be used with any built-in type or 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 oftemplates. This approach providescompile-time polymorphism that is often more efficient than traditionalrun-time polymorphism. Modern C++compilers 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,abstractness without loss of efficiency, theVon Neumann computation model,[2] andvalue semantics.

The STL and theC++ Standard Library are two distinct entities[3], though sometimes the parts of the C++ Standard Library directly influenced/inherited from the STL are called "the STL".[4]

History

[edit]
Main article:History of the Standard Template Library

In November 1993Alexander Stepanov presented a library based on generic programming to theANSI/ISO committee for C++ standardization. The committee's response was overwhelmingly favorable and led to a request fromAndrew 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 containers) had to be shown to be consistent by fully implementing them, a task Stepanov delegated toDavid Musser. 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 theInternet 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

[edit]

Containers

[edit]

The STL contains sequencecontainers and associative containers. The containers are objects that store data. The standardsequence containers includevector,deque, andlist. The standardassociative containers areset,multiset,map,multimap,hash_set,hash_map,hash_multiset andhash_multimap. There are alsocontainer adaptorsqueue,priority_queue, andstack, that are containers with specific interface, using other containers as implementation.

ContainerDescription
Simple containers
pairThe 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
vectoradynamic array, likeC array (i.e., capable ofrandom access) with the ability to resize itself automatically when inserting or erasing an object. Inserting an element to the back of the vector at the end takesamortized 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 optimization for typebool exists, which can optimize for space by grouping bool values together.[5]

listadoubly 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
asingly 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 asforward_list.
deque (double-endedqueue)a vector with insertion/erase at the beginning or end inamortized constant time, however lacking some guarantees on iterator validity after altering the deque.
Container adaptors
queueProvidesFIFOqueue interface in terms ofpush/pop/front/back operations.

Any sequence supporting operationsfront(),back(),push_back(), andpop_front() can be used to instantiate queue (e.g.list anddeque).

priority queueProvidespriority queue interface in terms ofpush/pop/top operations (the element with the highest priority is on top).

Anyrandom-access sequence supporting operationsfront(),push_back(), andpop_back() can be used to instantiate priority_queue (e.g.vector anddeque). It is implemented using aheap.

Elements should additionally support comparison (to determine which element has a higher priority and should be popped first).

stackProvidesLIFOstack interface in terms ofpush/pop/top operations (the last-inserted element is on top).

Any sequence supporting operationsback(),push_back(), andpop_back() can be used to instantiate stack (e.g.vector,list, anddeque).

Associative containers: unordered collections
seta mathematicalset; inserting/erasing elements in a set does not invalidate iterators pointing in the set. Provides set operationsunion,intersection,difference,symmetric difference and test of inclusion. Type of data must implement comparison operator< or custom comparator function must be specified; such comparison operator or comparator function must guaranteestrict weak ordering, otherwise behavior is undefined. Typically implemented using aself-balancing binary search tree.
multisetsame as a set, but allows duplicate elements (mathematicalmultiset).
mapanassociative array; allows mapping from one data item (a key) to another (a value). Type of key must implement comparison operator< or custom comparator function must be specified; such comparison operator or comparator function must guaranteestrict weak ordering, otherwise behavior is undefined. Typically implemented using a self-balancing binary search tree.
multimapsame 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 ahash table; keys are not ordered, but ahash function must exist for the key type. These types were left out of the C++ standard; similar containers were standardized inC++11, but with different names (unordered_set andunordered_map).
Other types of containers
bitsetstores series of bits similar to a fixed-sized vector of bools. Implements bitwise operations and lacks iterators. Not a sequence. Provides random access.
valarrayAnother array data type, intended for numerical use (especially to representvectors andmatrices); 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", andexpression template libraries are to be preferred.[6] A proposed rewrite of thevalarray part of the standard in this vein was rejected, instead becoming a permission to implement it using expression template.[7]

Iterators

[edit]

The STL implements five different types ofiterators. These areinput 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) andrandom-access iterators (that can move freely any number of steps in one operation).

A fundamental STL concept is arange 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.[8]

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 anddeques. User-createdcontainers 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 anassociative container 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

[edit]

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 likebinary_search andlower_bound usebinary search 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 guaranteestrict weak ordering. 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 performunion,intersection,difference of sorted ranges.

Functions

[edit]

The STL includes classes thatoverload the function call operator (operator()). Instances of such classes are called functors orfunction objects. Functors allow the behavior of the associated function to be parameterized (e.g. through arguments passed to the functor'sconstructor) 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 thepredicate. For example, algorithms likefind_if take aunary predicate that operates on the elements of a sequence. Algorithms like sort, partial_sort, nth_element and all sortedcontainers use abinary predicate that must provide astrict weak ordering, that is, it must behave like amembership test on a transitive, non-reflexive and asymmetricbinary relation. If none is supplied, these algorithms and containers useless by default, which in turn calls the less-than-operator <.

Criticisms

[edit]
This"criticism" or "controversy" sectionmay compromise the article'sneutrality. Please helpintegrate negative information into other sections or removeundue focus on minor aspects throughdiscussion on thetalk page.(August 2025)

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 andprettyprint STL-related error messages to make them more comprehensible.
  • Careless use of templates can lead tocode bloat.[9] 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 include:

  • Initialization of STLcontainers with constants within the source code is not as easy as data structures inherited from C (addressed inC++11 withinitializer 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.[10][11]
  • Theconcept 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 exampleJava.Ranges have been proposed as a safer, more flexible alternative to iterators.[12]
  • Certain iteration patterns such as callback enumeration APIs cannot be made to fit the STL model without the use ofcoroutines,[13] which were outside the C++ standard until C++20.
  • Compiler compliance does not guarantee thatAllocator objects, used for memory management forcontainers, 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 inC++11).
  • The set of algorithms is not complete: for example, thecopy_if algorithm was left out,[14] though it has been added inC++11.[15]

Implementations

[edit]

See also

[edit]

Notes

[edit]
  1. ^Holzner, Steven (2001).C++ : Black Book. Scottsdale, Ariz.: Coriolis Group. p. 648.ISBN 1-57610-777-9.The STL is made up ofcontainers,iterators,function objects, andalgorithms
  2. ^Musser, David (2001).STL tutorial and reference guide: C++ programming with the standard template library.Addison Wesley.ISBN 0-201-37923-6.
  3. ^Lightness Races in Orbit (5 March 2011)."What's the difference between "STL" and "C++ Standard Library"?". Stack Overflow. Retrieved21 October 2021.
  4. ^C++ Standards Committee. (2021).P2412R0 - Further refinements to the C++ Modules Design. Retrieved fromhttps://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2412r0.pdfArchived 20 November 2024(Date mismatch) at theWayback Machine
  5. ^"[vector.bool]".Eelis. Retrieved22 December 2024.
  6. ^Josuttis, Nicolai M. (1999).The C++ Standard Library: A Tutorial and Handbook. Addison-Wesley Professional. p. 547.ISBN 9780201379266.
  7. ^Vandevoorde, David; Josuttis, Nicolai M. (2002).C++ Templates: The Complete Guide.Addison Wesley.ISBN 0-201-73484-2.
  8. ^Stepanov, Alexander; Lee, Meng (31 October 1995)."The Standard Template Library"(PDF). Retrieved16 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.
  9. ^Adrian Stone."Minimizing Code Bloat: Template Overspecialization".
  10. ^Meyers, Scott (2005).Effective C++ Third Edition – 55 Specific Ways to Improve Your Designs.Addison Wesley.ISBN 0-321-33487-6.
  11. ^Sutter, Herb;Alexandrescu, Andrei (2004).C++ Coding Standards: 101 Rules, Guidelines, and Best Practices. Addison-Wesley.ISBN 0-321-11358-6.
  12. ^Andrei Alexandrescu (6 May 2009)."Iterators Must Go"(PDF). BoostCon 2009. Retrieved19 March 2011.
  13. ^Matthew Wilson (February 2004)."Callback Enumeration APIs & the Input Iterator Concept".Dr. Dobb's Journal.
  14. ^Bjarne Stroustrup (2000).The C++ Programming Language (3rd ed.). Addison-Wesley.ISBN 0-201-70073-5.: p.530 
  15. ^More STL algorithms (revision 2)
  16. ^"Apache C++ Standard Library".stdcxx.apache.org. Retrieved1 March 2023.

References

[edit]

External links

[edit]
Features
Standard Library
Ideas
Compilers
IDEs
Superset languages
Dialects
Relative to
other languages
People
Retrieved from "https://en.wikipedia.org/w/index.php?title=Standard_Template_Library&oldid=1337488420"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp