Standard Template Library

The Standard Template Library (STL) is a software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called algorithms, containers, functions, and iterators.[1]

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 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 of templates. This approach provides compile-time polymorphism that is often more efficient than traditional run-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, 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 Alexander Stepanov 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 containers) had to be shown to be consistent by fully implementing them, a task Stepanov delegated to David 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 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 containers and associative containers. The containers are objects that store data. The standard sequence containers include vector, deque, and list. The standard associative containers are set, 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 dynamic array, like C array (i.e., capable of random 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 takes 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.
deque (double-ended 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 FIFO queue interface in terms of push/pop/front/back operations.

Any sequence supporting operations front(), back(), push_back(), and pop_front() can be used to instantiate queue (e.g. list and deque).

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 heap.

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

stack Provides LIFO stack interface in terms of push/pop/top operations (the last-inserted element is on top).

Any sequence supporting operations back(), push_back(), and pop_back() can be used to instantiate stack (e.g. vector, list, and deque).

Associative containers: unordered collections
set a mathematical set; inserting/erasing elements in a set does not invalidate iterators pointing in the set. Provides set operations union, 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 guarantee 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 associative 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 guarantee 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 deques. User-created containers 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 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 binary_search and lower_bound use binary 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 guarantee strict 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 perform union, intersection, difference of sorted ranges.

Functors

The STL includes classes that overload the function call operator (operator()). Instances of such classes are called functors or function objects. Functors allow the behavior of the associated function to be parameterized (e.g. through arguments passed to the functor's constructor) 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. For example, algorithms like find_if take a unary predicate that operates on the elements of a sequence. Algorithms like sort, partial_sort, nth_element and all sorted containers use a binary predicate that must provide a strict weak ordering, that is, it must behave like a membership test on a transitive, non-reflexive and asymmetric binary relation. If none is supplied, these algorithms and containers use less by 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 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 concept 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. 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 Allocator objects, used for memory management for 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

See also

Notes

  1. ^ Holzner, Steven (2001). C++ : Black Book. Scottsdale, Ariz.: Coriolis Group. p. 648. ISBN 1-57610-777-9. The STL is made up of containers, iterators, function objects, and algorithms
  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. Retrieved 21 October 2021.
  4. ^ Josuttis, Nicolai M. (1999). The C++ Standard Library: A Tutorial and Handbook. Addison-Wesley Professional. p. 547. ISBN 9780201379266.
  5. ^ Vandevoorde, David; Josuttis, Nicolai M. (2002). C++ Templates: The Complete Guide. Addison Wesley. ISBN 0-201-73484-2.
  6. ^ 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.
  7. ^ Adrian Stone. "Minimizing Code Bloat: Template Overspecialization".
  8. ^ Meyers, Scott (2005). Effective C++ Third Edition – 55 Specific Ways to Improve Your Designs. Addison Wesley. ISBN 0-321-33487-6.
  9. ^ Sutter, Herb; Alexandrescu, Andrei (2004). C++ Coding Standards: 101 Rules, Guidelines, and Best Practices. Addison-Wesley. ISBN 0-321-11358-6.
  10. ^ Andrei Alexandrescu (6 May 2009). "Iterators Must Go" (PDF). BoostCon 2009. Retrieved 19 March 2011.
  11. ^ Matthew Wilson (February 2004). "Callback Enumeration APIs & the Input Iterator Concept". Dr. Dobb's Journal.
  12. ^ Bjarne Stroustrup (2000). The C++ Programming Language (3rd ed.). Addison-Wesley. ISBN 0-201-70073-5.: p.530 
  13. ^ More STL algorithms (revision 2)
  14. ^ "Apache C++ Standard Library". stdcxx.apache.org. Retrieved 1 March 2023.

References

Read other articles:

The Descendants First editionAuthorKaui Hart HemmingsCountryUnited StatesLanguageEnglishGenreFictionPublisherRandom HousePublication dateMay 15, 2007Media typePrintPages304 (First Edition)ISBN1-4000-6633-6 The Descendants is a novel written by Kaui Hart Hemmings. The 2011 American film The Descendants, directed by Alexander Payne, with the adapted screenplay by Payne, Nat Faxon, and Jim Rash,[1] is based on this novel.[2] Plot summary Matthew King was once considered one...

 

 

Christian Benteke Benteke bersama Tim nasional sepak bola Belgia pada 2017Informasi pribadiNama lengkap Christian Benteke Liolo[1]Tanggal lahir 3 Desember 1990 (umur 33)Tempat lahir Kinshasa, Zaire[2]Tinggi 190 cm (6 ft 3 in)[3]Posisi bermain PenyerangInformasi klubKlub saat ini D.C. UnitedKarier junior1996–2004 JS Pierreuse2004–2006 Standard Liège2006–2007 GenkKarier senior*Tahun Tim Tampil (Gol)2007–2008 Genk 10 (1)2009–2011 Standard L...

 

 

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Peder, Košice-okolie District – news · newspapers · books · scholar · JSTOR (August 2008) (Learn how and when to remove this template message) Košice-okolie District in the Kosice Region Peder (Hungarian: Péder) is a village and municipality in Košice-okoli...

Entertainment investment firm Saban Entertainment Group redirects here. For the former television production company that could be considered a predecessor, see Saban Entertainment. Saban Capital Group LLCCompany typePrivateIndustryPrivate equityEntertainmentMediaMerchandisingCommunicationsPredecessorSaban EntertainmentFounded2001; 23 years ago (2001)FounderHaim SabanHeadquartersLos Angeles, California, U.S.Area servedWorldwideKey peopleHaim Saban (Chairman, CEO)Adam Chesnof...

 

 

Mike Huckabee Mike Huckabee en 2015. Fonctions 44e gouverneur de l'Arkansas 15 juillet 1996 – 9 janvier 2007(10 ans, 5 mois et 25 jours) Prédécesseur Jim Guy Tucker Successeur Mike Beebe 12e lieutenant-gouverneur de l'Arkansas 20 novembre 1993 – 15 juillet 1996(2 ans, 7 mois et 25 jours) Prédécesseur Jim Guy Tucker Successeur Winthrop Paul Rockefeller Biographie Nom de naissance Michael Dale Huckabee Date de naissance 24 août 1955 (68 ans) Lieu de ...

 

 

Pour les articles homonymes, voir Feu (homonymie), Feu rouge et Feu rouge clignotant. Si ce bandeau n'est plus pertinent, retirez-le. Cliquez ici pour en savoir plus. Cet article adopte un point de vue régional ou culturel particulier et nécessite une internationalisation (avril 2021). Merci de l'améliorer ou d'en discuter sur sa page de discussion ! Vous pouvez préciser les sections à internationaliser en utilisant {{section à internationaliser}}. Les trois états d'un feu tricol...

Dana Moneter Internasional Logo Kantor pusat DMI di Washington, D. C., Amerika SerikatDataNama singkatFMI, FMI, FMI, FMI, FMI, FMI, FMI, FMI, IMF, IMA, IMF, IWF, FMI, IMF, NDF, MMF, FME, MMF, ΔΝΤ, HPF, ХПФ, AGS, IMF, FMI, DMI, SVF, IGF, MFW, FMI, MMF, MDS, FMN, XVF, FMI, XVJ, ХВЖ, MMF, ММФ, MMF, СБП, ไอเอ็มเอฟ, FMI, ԱՄՀ, CAI, TVF, МВФ, МВФ, ХВФ, YMF, ЭВФ, ОУВС, МВФ, MMF, МВФ, FMI, 아이엠에프, ХААФ, სსფ, IMF, ММФ, ХВ...

 

 

此條目没有列出任何参考或来源。 (2013年2月8日)維基百科所有的內容都應該可供查證。请协助補充可靠来源以改善这篇条目。无法查证的內容可能會因為異議提出而被移除。 莱奥波尔多·加尔铁里Leopoldo Fortunato Galtieri Castelli 阿根廷总统(實質)任期1981年12月22日—1982年6月18日副总统Víctor Martínez前任卡洛斯·拉科斯特继任阿尔弗雷多·奥斯卡·圣琼 个人资料出生(1926-07-15)1926�...

 

 

森川智之配音演员本名同上原文名森川 智之(もりかわ としゆき)罗马拼音Morikawa Toshiyuki昵称モリモリ[1]、帝王[1]国籍 日本出生 (1967-01-26) 1967年1月26日(57歲) 日本東京都品川區[1](神奈川縣川崎市[2]、橫濱市[3]成長)职业配音員、旁白、歌手、藝人音乐类型J-POP出道作品外國人取向的日語教材代表作品但丁(Devil May Cry)D-boy(宇宙騎...

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (أبريل 2020) خريطة تظهر المنتخبات الأفريقية حسب عدد أفضل إنجازاتها في نهائيات كأس الأمم الأفريقيةأقيمت أول نسخة لبطول...

 

 

بومباردييه داش 8 Dash 8 / Q-Seriesمعلومات عامةالنوع طائرة رحلات جويةبلد الأصل  كنداالمهام طيران تجاري سعر الوحدة 12.5 مليون دولار أمريكي Q100 13 مليون دولار أمريكي Q200 17 مليون دولار أمريكي Q300 Q400 27 مليون دولار أمريكي [2]التطوير والتصنيعالصانع دي هافيلاند كندا - تورونتو بومباردييه �...

 

 

MEA technology company This article is about the company. For the cycling team, see Dimension Data (cycling team). Dimension DataCompany typePrivateIndustryInformation technologyFounded1983HeadquartersJohannesburg, South AfricaArea servedGlobalKey peopleAlan Turnley-Jones (CEO), Barry Curtin (CFO), Jay Reddy (CDO)[1]Services Managed services System integration Consulting Security Education and learning Revenue$7.5 billion (2014)ParentNippon Telegraph and TelephoneSubsidiaries 17 subsi...

Brazilian diver (born 1996) Luana LiraLuana Lira in 2016Personal informationBorn (1996-03-05) 5 March 1996 (age 28)SportCountryBrazilSportDiving Medal record Women's diving Representing  Brazil South American Games 2022 Asunción 1 m springboard Military World Games 2019 Wuhan Team Luana Wanderley Moreira Lira (born 5 March 1996)[1] is a Brazilian diver. She represented Brazil at the World Aquatics Championships in 2015, 2017, 2019 and 2022. She represented Brazil at the 202...

 

 

Artikel ini bukan mengenai Kerajaan Rusia. Kerajaan PrusiaKönigreich Preußen1701–1918 Bendera Lambang Lagu kebangsaan: PreußenliedLagu Prusia Heil dir im Siegerkranz (keduanya tidak resmi)Kerajaan Prusia Pada 1812 Pada Perang NapoleonIbu kotaBerlinBahasa resmiBahasa JermanPemerintahanMonarki• 1701 — 1713 Friedrich I (pertama)• 1888 — 1918 Wilhelm II (terakhir) Perdana Menteri1 • 1848 Adolf Heinrich von Arnim-Boitzenburg (pertama)• 1918 Maximilian...

 

 

American space scientist James Van AllenVan Allen at the National Air and Space Museum, 1977BornJames Alfred Van Allen(1914-09-07)September 7, 1914Mount Pleasant, Iowa, USDiedAugust 9, 2006(2006-08-09) (aged 91)Iowa City, Iowa, USEducationIowa Wesleyan College B.S.University of Iowa (M.S., Ph.D.)Known forVan Allen radiation beltsMagnetospheric physics[1]AwardsTime magazine Man of the Year (1960)Elliott Cresson Medal (1961)William Bowie Medal (1977)National Medal of Science (...

Hydrogen ship Xperiance NX hydrogen The Xperiance NX hydrogen is a 12-person hydrogen ship, power-assisted by an electric motor that gets its electricity from a fuel cell. The debut was on 23 June 2006 at Leeuwarden, Netherlands.[1] Refueling The boats are refuelled with exchangeable tanks. Specifications Boat 7 m long, width 2.35 m, draft 0.50 m, 4 exchangeable 200 bar (20 MPa), 30 liter hydrogen tanks, with a 1.2 kW PEM fuel cell and a 12 kW·h battery for 12 passengers. Its ra...

 

 

Japanese light novel series and its franchise How a Realist Hero Rebuilt the KingdomFirst light novel volume cover, featuring Liscia Elfrieden (front) and Kazuya Souma (back)現実主義勇者の王国再建記(Genjitsu Shugi Yūsha no Ōkoku Saikenki)GenreFantasy comedy[1]Harem[2]Isekai[1] Novel seriesWritten byDojyomaruPublished byShōsetsuka ni Narō (2014–2016)Pixiv (2016–present)Original run2014 – present Light novelWritten byDojyomaruIllustra...

 

 

Road in England For the Samsung phone with model numbers beginning A217, see Samsung Galaxy A21s. A217The A217 running through Lower KingswoodMajor junctionsNorth endFulhamMajor intersections A308 A3205 A214 A3 A24 A216 A236 A239 A297 A232 A2022 A240 M25 A25 A2044 A23South endGatwick LocationCountryUnited KingdomPrimarydestinationsSutton, Reigate Road network Roads in the United Kingdom Motorways A and B road zones The A217 is a road in London and Surrey in England. It runs north–...

IV Copa de Naciones de la WAFUGhana Ghana 2013 Go!TV WAFU Cup Fecha 21 de noviembre[1]​ de 201328 de noviembre de 2013 Cantidad de equipos 8 Podio • Campeón• Subcampeón• Tercer lugar• Cuarto lugar  Ghana GhanaSenegal SenegalTogo TogoBenín Benín Partidos 14 Goles anotados 43 (3,07 por partido) Goleador Saibou Badarou (4) La Copa de Naciones de la WAFU 2013, conocida como Go!TV WAFU Cup por razones de patrocinio, fue la 4º edición de este ...

 

 

Daytona International SpeedwayLogo Daytona International Speedway.Lokasi1801 West International Speedway Blvd,Daytona Beach, Florida 32114Zona waktuUTC-5 (UTC-4 DST)Kapasitas101,500–167,785 (w/ infield, depending on configuration) 123,500 (grandstand capacity)PemilikDaytona Beach Racing & Recreational Facilities District[1]PengelolaNASCARBroke ground1957; 67 tahun lalu (1957)Dibuka1959; 65 tahun lalu (1959)Biaya pembangunanUS$3 millionArsitekCharles MoneypennyWill...