Вы находитесь на странице: 1из 41

Standard Template Library Page 1

Table of Contents
C++ Overview .....................................................................................................................................3
C++ with Standard Template Library...................................................................................................4
History..................................................................................................................................................
Overview ! STL...................................................................................................................................."
Overview #ontainers$ iterators$ algorithms...........................................................................................%
&terators Preview...................................................................................................................................'
&terator Sort ()ample...........................................................................................................................*
&terator................................................................................................................................................1+
&terator #ategories..........................................................................................................................1+
&terator Classes...................................................................................................................................1,
Primitives.......................................................................................................................................1,
-daptors.........................................................................................................................................1,
Stream &terators..............................................................................................................................1,
./n#tions -daptors........................................................................................................................1,
./n#tions Operations.....................................................................................................................13
0ange...............................................................................................................................13
1on!member operators..................................................................................................................13
&terators ()ample...........................................................................................................................1
&terator adaptors.............................................................................................................................1"
istream2iterator.........................................................................................................................1"
&terator -daptor ()ample...................................................................................................................1%
Templates ...........................................................................................................................................1'
3e4ining a Template.......................................................................................................................1*
./n#tion Template 3e4inition ()ample.........................................................................................,+
./n#tion templates ()ample..........................................................................................................,1
./n#tion Template 5ariations ()ample.........................................................................................,,
Class templates..............................................................................................................................,4
Class Template ()ample................................................................................................................,
introd/#ing the ve#tor template.....................................................................................................,"
STL #omponents.................................................................................................................................,%
Containers......................................................................................................................................,%
Hierar#hy.......................................................................................................................................,'
Se6/en#es..................................................................................................................................,'
5e#tors..................................................................................................................................,'
Lists......................................................................................................................................,'
3e6/es..................................................................................................................................,'
Sta#7s and 6/e/es.................................................................................................................,*
-sso#iative #ontainers...............................................................................................................,*
Sets.......................................................................................................................................,*
8/ltisets...............................................................................................................................,*
8aps.....................................................................................................................................,*
8/ltimaps.............................................................................................................................,*
priority 6/e/e$ .....................................................................................................................,*
bit ve#tor$ .............................................................................................................................,*
6/e/e....................................................................................................................................,*
()ample /sing #ontainer algorithms..............................................................................................3+
Container S/mmary Table..................................................................................................................31
Simple Containers..........................................................................................................................31
Container -daptors........................................................................................................................3,
Standard Template Library Page ,
Containers 9 -sso#iative and other types......................................................................................33
-lgorithms..........................................................................................................................................34
-lgorithms library..........................................................................................................................34
1on!modi4ying se6/en#e operations.............................................................................................34
8odi4ying se6/en#e operations.....................................................................................................3
Partitioning operations...................................................................................................................3"
Sorting operations :on sorted ranges;............................................................................................3"
<inary sear#h operations :on sorted ranges;..................................................................................3%
Set operations :on sorted ranges;...................................................................................................3%
Heap operations.............................................................................................................................3'
8inim/m=ma)im/m operations....................................................................................................3'
1/meri# operations........................................................................................................................3*
C library.........................................................................................................................................3*
./n#tors..............................................................................................................................................4+
C++ Standard Library.........................................................................................................................41
C++ Standard Library....................................................................................................................4,
Standard Template Library Page 3
C++ Overview
#s.brown.ed/
3ata abstra#tion separates the inter4a#e :how the ob>e#t is /sed; 4rom the implementation :how it
wor7s &nside;.
0elationships between ob>e#ts and types are 4/ndamental in ob>e#t!oriented programming?
inheritan#e de4ines a relationship between types #orresponding to @is!aA$ aggregation #orresponds to
@has!aA$ and asso#iations are more general relationships
Beneri# programming is a notion that has gained a lot o4 pop/larity in the last 4ew years? originally
/sed in -da$ the Standard Template Library :ro/ghly a s/bset o4 the standard C++ library; made it
pop/lar in C++.
Standard Template Library Page 4
C++ with Standard Template Library
Containers are ob>e#ts that #ontain other ob>e#ts$ e.g.$ ve#tor$ set$ map.
,. &terators represent lo#ations in a #ontainer. (a#h #ontainer has its own iterator type.
3. -lgorithms are operations on #ontainers$ e.g.$ 4ind$ sort$ random2sh/44le.
4. ./n#tors are operations on ob>e#ts$ e.g.$ less$ pl/s.
. -daptors are ob>e#ts that #hange an inter4a#e$ e.g.$ not1. :ThatCs a one at the end$ not an ell? there
is also a not,.;
". Dtilities are #omponents s/#h as pairs$ operations li7e #omparison$ et#. &n the -1S& standard$
allo#ators are in#l/ded in the /tilities se#tion.
%. 3iagnosti#s are provided to deal with e)#eptions.
'. Lo#ales 4a#ilitate internationaliEation.
*. 1/meri#s are #ontainer types that are optimiEed 4or speed$ less general than #ontainers$ e.g.$
valarray$ #omple).
1+. Strings repla#e CFs #hara#ter arrays.
11. Streams are /sed 4or inp/t and o/tp/t.
1,. -llo#ators #/stomiEe memory allo#ation$ e.g.$ mallo#2allo#.
Standard Template Library Page
History
The ar#hite#t/re o4 STL is largely the #reation o4 one person$ -le)ander Stepanov.
&n 1*%* he began wor7ing o/t his initial ideas o4 generi# programming and e)ploring their potential
4or revol/tioniEing so4tware development. -ltho/gh 3avid 8/sser had developed and advo#ated
some aspe#ts o4 generi# programming already by year 1*%1$ it was limited to a rather spe#ialiEed
area o4 so4tware development :#omp/ter algebra;.
Stepanov re#ogniEed the 4/ll potential 4or generi# programming and pers/aded his then!#olleag/es
at Beneral (le#tri# 0esear#h and 3evelopment :in#l/ding$ primarily$ 3avid 8/sser and 3eepa7
Gap/r; that generi# programming sho/ld be p/rs/ed as a #omprehensive basis 4or so4tware
development. -t the time there was no real s/pport in any programming lang/age 4or generi#
programming.
The 4irst ma>or lang/age to provide s/#h s/pport was -da$ with its generi# /nits 4eat/re. <y 1*'%
Stepanov and 8/sser had developed and p/blished an -da library 4or list pro#essing that embodied
the res/lts o4 m/#h o4 their resear#h on generi# programming.
The reason 4or t/rning to C++$ whi#h Stepanov was the C=C++ model o4 #omp/tation whi#h allows
very 4le)ible a##ess to storage via pointers is #r/#ial to a#hieving generality witho/t losing
e44i#ien#y.
Stepanov e)perimented with many ar#hite#t/ral and algorithm 4orm/lations$ 4irst in C and later in
C++. 8/sser #ollaborated in this resear#h and in 1**, 8eng Lee >oined StepanovCs pro>e#t at HP
and be#ame a ma>or #ontrib/tor.
-ndrew Goenig o4 <ell Labs had not be#ome aware o4 the wor7 and as7ed Stepanov to present the
main ideas at a 1ovember 1**3 meeting o4 the -1S&=&SO #ommittee 4or C++ standardiEation. The
#ommitteeCs response was overwhelmingly 4avorable and led to a re6/est 4rom Goenig 4or a 4ormal
proposal in time 4or the 8ar#h 1**4 meeting.
S/bse6/ently$ the Stepanov and Lee do#/ment 1% was in#orporated into the -1S&=&SO C++ dra4t
standard :1$ parts o4 #la/ses 1% thro/gh ,%;. &t also in4l/en#ed other parts o4 the C++ Standard
Library$ s/#h as the string 4a#ilities$ and some o4 the previo/sly adopted standards in those areas
were revised a##ordingly
The prospe#ts 4or early widespread dissemination o4 STL were #onsiderably improved with
Hewlett!Pa#7ardCs de#ision to ma7e its implementation 4reely available on the &nternet in -/g/st
1**4. This implementation$ developed by Stepanov$ Lee$ and 8/sser d/ring the standardiEation
pro#ess$ be#ame the basis o4 many implementations o44ered by #ompiler and library vendors today.
Standard Template Library Page "
Overview - STL
The STL provides a ready!made set o4 #ommon #lasses 4or C++$H
#ontainers and asso#iative arrays$
that #an be /sed with any b/ilt!in type or with any /ser!de4ined type
s/pports operations s/#h as #opying and assignment
STL algorithms are independent o4 #ontainers ! signi4i#antly red/#es the #omple)ity o4 the library.
The STL a#hieves its res/lts thro/gh the /se o4 templates
This approa#h provides
#ompile!time polymorphism
is o4ten more e44i#ient than traditional r/n!time polymorphism.
The STL was #reated as the 4irst library o4 generi# algorithms and data str/#t/res 4or C++$ with 4o/r
ideas in mindH
1. generi# programming$
,. abstra#tness witho/t loss o4 e44i#ien#y$
3. the 5on 1e/mann #omp/tation model$
4. and val/e semanti#s.
httpH==www.the4/llwi7i.org=Standard2Template2Library
Standard Template Library Page %
Overview containers, iterators, algorithms
STL provides a n/mber o4 #ontainer types$ representing ob>e#ts that #ontain other
ob>e#ts.
One o4 these #ontainers is a #lass #alled vector that behaves li7e an array$ b/t #an
grow itsel4 as ne#essary. One o4 the operations on ve#tor is push_back$ whi#h p/shes
an element onto the end o4 the ve#tor :growing it by one;.
- ve#tor #ontains a blo#7 o4 contiguous initialiEed elements !! i4 element inde) 7 has
been initialiEed$ then so have all the ones with indi#es less than 7.
- ve#tor #an be presized$ s/pplying the siEe at #onstr/#tion$ and yo/ #an as7 a ve#tor
how many elements it has with size. This is the logical n/mber o4 elements !! the
n/mber o4 elements /p to the highest!inde)ed one yo/ have /sed. There is also a
notion o4 capacity !! the n/mber o4 elements the ve#tor #an hold be4ore reallo#ating.
httpH==#s.brown.ed/=I>a7=proglang=#pp=stlt/t=t/t.html
Standard Template Library Page '
Iterators review
&terators provide a way o4 spe#i4ying a position in a #ontainer.
-n iterator #an be incremented or dereferenced$ and two iterators #an be compared.
There is a spe#ial iterator val/e #alled Jpast!the!endJ.
Ko/ #an as7 a ve#tor 4or an iterator that points to the 4irst element with the message
begin. Ko/ #an get a past!the!end iterator with the message end. The #ode
vector<int> v;
// add some integers to v
vector::iterator i1 = v.begin();
vector::iterator i2 = v.end();
will #reate two iterators li7e thisH
Operations li7e sort ta7e two iterators to spe#i4y the so/r#e range.
To get the so/r#e elements$ they in#rement and dere4eren#e the 4irst iterator /ntil it is
e6/al to the se#ond iterator. 1ote that this is a semi!open rangeH it in#l/des the start
b/t not the end.
Two ve#tor iterators #ompare e6/al i4 they re4er to the same element o4 the same
ve#tor.
Standard Template Library Page *
Iterator Sort !"ample
P/tting this together$ here is the new programH
#include <string.h>
#include <algo.h>
#include <vector.h>
#include <stdlib.h>
#include <iostream.h>

main ()
{
vector<int> v; // create an emt! vector o" integers
int inut;
#hile (cin >> inut) // #hile not end o" "ile
v.ush$bac% (inut); // aend to vector

// sort ta%es t#o random iterators& and sorts the elements bet#een
// them. 's is al#a!s the case in ()*& this includes the value
// re"erred to b! "irst but not the one re"erred to b! last; indeed&
// this is o"ten the ast+the+end value& and is there"ore not
// dere"erenceable.
sort(v.begin()& v.end());

int n = v.si,e();
"or (int i = -; i < n; i..)
cout << v/i0 << 12n1;
3
Standard Template Library Page 1+
Iterator
LiteratorM
&terator de4initions
In C++, an iterator is any object that, pointing to some element in a range of elements (such
as an array or a container), has the ability to iterate through the elements of that range using a
set of operators (at least, the increment (..) and dereference (4) operators).
The most obvious form of iterator is a pointer: pointer can point to elements in an array, and
can iterate through them using the increment operator (..). !ut other forms of iterators e"ist.
#or e"ample, each container type (such as a vector) has a specific iterator type designed to
iterate through its elements in an efficient $ay.
%otice that $hile a pointer is a form of iterator, not all iterators have the same functionality a
pointer has& To distinguish bet$een the re'uirements an iterator shall have for a specific
algorithm, five different iterator categoriese"ist:
Iterator categories
&terators are #lassi4ied in 4ive #ategories depending on the 4/n#tionality they implementH
RandomAccess Bidirectional Forward Input
Output
In this graph, each iterator category implements the functionalities of all categories to its right:
Input and output iterators are the most limited types of iterators, speciali(ed in performing only
se'uential input or output operations.
#or$ard iterators have all the functionality of input and output iterators, although they are
limited to one direction in $hich to iterate through a range.
!idirectional iterators can be iterated through in both directions. ll standard
containers support at least bidirectional iterators types.
)andom access iterators implement all the functionalities of bidirectional iterators, plus, they
have the ability to access ranges non*se'uentially: offsets can be directly applied to these
iterators $ithout iterating through all the elements in bet$een. This provides these iterators
$ith the same functionality as standard pointers (pointers are iterators of this category).
httpH==www.#pl/spl/s.#om=re4eren#e=iterator=
Standard Template Library Page 11
The characteristics of each category of iterators are:
category characteristic
valid
epressions
all #ategories
Can be #opied and #opy!#onstr/#ted
5 b(a);
b = a;
Can be in#remented
..a
a..
4a..
0andom
-##ess
<idire#tional
.orward
&np/t
-##epts e6/ality=ine6/ality
#omparisons
a == b
a 6= b
Can be dere4eren#ed as an rvalue
4a
a+>m
O/tp/t
Can be dere4eren#ed to be the le4t side
o4 an assignment operation
4a = t
4a.. = t
Can be de4a/lt!#onstr/#ted
5 a;
5()
Can be de#remented
++a
a++
4a++
S/pports arithmeti# operators . and +
a . n
n . a
a + n
a + b
S/pports ine6/ality #omparisons
:<$ >$ <= and >=; between iterators
a < b
a > b
a <= b
a >= b
S/pports #ompo/nd assignment
operations .= and +=
a .= n
a += n
S/pports o44set dere4eren#e operator
:/0;
a/n0
+here 5 is an iterator type, a and b are objects of this iterator type, t is an
object of the type pointed by the iterator type, and n is an integer value.
)andom access iterators have all characteristics. !idirectional iterators have a
subset of random access iterators,s.#or$ard iterators have a subset
of bidirectional iterators,s. nd input and output have each their o$n subset of
for$ard iterator,s.
Standard Template Library Page 1,
Iterator Classes
Primitives
iterator
the basi# iterator
:#lass template;
input_iterator_tag
output_iterator_tag
forward_iterator_tag
bidirectional_iterator_tag
random_access_iterator_tag
empty #lass types /sed to indi#ate iterator #ategories
:#lass;
iterator_traits
provides /ni4orm inter4a#e to the properties o4 an iterator
:#lass template;
Adaptors
reverse_iterator
iterator adaptor 4or reverse!order traversal
:#lass template;
move_iterator
:C++11;
iterator adaptor whi#h dere4eren#es to an rval/e re4eren#e
:#lass template;
back_insert_iterator
iterator adaptor 4or insertion at the end o4 a #ontainer
:#lass template;
front_insert_iterator
iterator adaptor 4or insertion at the 4ront o4 a #ontainer
:#lass template;
insert_iterator
iterator adaptor 4or insertion into a #ontainer
:#lass template;
Stream Iterators
istream_iterator
inp/t iterator that reads 4rom std::basic_istream
:#lass template;
ostream_iterator
o/tp/t iterator that writes to std::basic_ostream
:#lass template;
istreambuf_iterator
inp/t iterator that reads
4rom std::basic_streambuf
:#lass template;
ostreambuf_iterator
o/tp/t iterator that writes to std::basic_streambuf
:#lass template;
Standard Template Library Page 13
Functions Adaptors
make_move_iterator
:C++11;
#reates a std::move_iterator o4 type in4erred 4rom the
arg/ment
:4/n#tion template;
front_inserter
#reates a std::front_insert_iterator o4 type in4erred 4rom
the arg/ment
:4/n#tion template;
back_inserter
#reates a std::back_insert_iterator o4 type in4erred 4rom
the arg/ment
:4/n#tion template;
inserter
#reates a std::insert_iterator o4 type in4erred 4rom the
arg/ment
:4/n#tion template;
Functions Operations
advance
advan#es an iterator by given distan#e
:4/n#tion;
distance
ret/rns the distan#e between two iterators
:4/n#tion;
next
:C++11;
in#rement an iterator
:4/n#tion;
prev
:C++11;
de#rement an iterator
:4/n#tion;
Range
begin
:C++11;
ret/rns an iterator to the beginning o4 a #ontainer or array
:4/n#tion;
end
:C++11;
ret/rns an iterator to the end o4 a #ontainer or array
:4/n#tion;
Non-member operators
operator==
operator!=
operator<
operator<=
operator>
operator>=
#ompares the /nderlying iterators
:4/n#tion template;
operator+
advan#es the iterator
:4/n#tion template;
operator-
#omp/tes the distan#e between two iterator adaptors
:4/n#tion template;
Standard Template Library Page 14
operator==
operator!=
operator<
operator<=
operator>
operator>=
#ompares the /nderlying iterators
:4/n#tion template;
operator+
advan#es the iterator
:4/n#tion template;
operator-
#omp/tes the distan#e between two iterator adaptors
:4/n#tion template;
operator==
operator!=
#ompares two istream2iterators
:4/n#tion template;
operator==
operator!=
#ompares two istreamb/42iterators
:4/n#tion template;
Standard Template Library Page 1
Iterators Example
httpH==www.yolin/).#om=TDTO0&-LS=Lin/)T/torialC++STL.html
#include <iostream>
#include <vector>
#include <string>
using namesace std;
main()
{
vector<string> ((;
((.ush$bac%(1)he number is 1-1);
((.ush$bac%(1)he number is 2-1);
((.ush$bac%(1)he number is 7-1);
cout << 1*oo b! inde8:1 << endl;
int ii;
"or(ii=-; ii < ((.si,e(); ii..)
{
cout << ((/ii0 << endl;
3
cout << endl << 19onstant :terator:1 << endl;
vector<string>::const$iterator cii;
"or(cii=((.begin(); cii6=((.end(); cii..)
{
cout << 4cii << endl;
3
cout << endl << 1;everse :terator:1 << endl;
vector<string>::reverse$iterator rii;
"or(rii=((.rbegin(); rii6=((.rend(); ..rii)
{
cout << 4rii << endl;
3
cout << endl << 1(amle <utut:1 << endl;
cout << ((.si,e() << endl;
cout << ((/20 << endl;
s#a(((/-0& ((/20);
cout << ((/20 << endl;
3
Standard Template Library Page 1"
Iterator adaptors
&n addition to iterating thro/gh #ontainers$ iterators #an iterate over streams$ either to
read elements or to write them.
-n inp/t stream li7e cin has the right 4/n#tionality 4or an inp/t iteratorH
it provides a##ess to a se6/en#e o4 elements.
The tro/ble is$ it has the wrong inter4a#e 4or an iteratorH
operations that /se iterators e)pe#t to be able to in#rement them and
dere4eren#e them.
STL provides adaptors$ types that trans4orm the inter4a#e o4 other types. This is very
m/#h how ele#tri#al adaptors wor7.
One very /se4/l adaptor is istream2iterator.
This is a template type? yo/ parameteriEe it by the type o4 ob>e#t yo/ want to read
4rom the stream. i.e. int$ #har$ 4loat$ et#..
istream_iterator
&n this #ase we want integers$ so we wo/ld /se an istream2iteratorLintM.
&stream iterators are initialiEed by giving them a stream
dere4eren#ing the iterator reads an element 4rom the stream$
in#rementing the iterator has no e44e#t.
-n istream iterator that is #reated with the de4a/lt #onstr/#torH
has the past!the!end val/e$
as does an iterator whose stream has rea#hed the end o4 4ile.
Standard Template Library Page 1%
Iterator #daptor !"ample
// include librar! "or each "eature used =>
// cre"erence.com
#include <algorithm> // sort
#include <vector> // vector
#include <iostream> //cin cout
#include <iterator> //iterators
int main ()
{
using namesace std;
// create a vector to hold numbers t!ed in
vector<int> v;
cout << 1?lease enter numbers (ctrl+@) ends seAuence1 << endl;
istream$iterator<int> start (cin); //inut iterator "rom stream
istream$iterator<int> end; // end o" stream iterator
bac%$insert$iterator<vector<int> > dest (v); // aend integers to vector
co! (start& end& dest); // co! cin numbers to vector
sort(v.begin()& v.end()); // sort the vector
co! (v.begin()& v.end()& ostream$iterator<int>(cout& 12n1)); // co! vector to cout
return -;
3
the ve#tor is
#opied into memory$
sorted$ and
#opied o/t again.
Standard Template Library Page 1'
Templates
-re a 4eat/re o4 the C++ programming lang/age that allow 4/n#tions and #lasses to operate with
generi# types.
#har
int
4loat
do/ble
str/#t/re
#lass
This allows a 4/n#tion or #lass to wor7 on many di44erent data types witho/t being rewritten 4or
ea#h one.
Templates are o4 great /tility to programmers in C++$ espe#ially when #ombined with m/ltiple
inheritan#e and operator overloading.
The C++ Standard Library provides many /se4/l 4/n#tions within a 4ramewor7 o4 #onne#ted
templates.
httpH==www.the4/llwi7i.org=Template2:programming;
Standard Template Library Page 1*
Defining a Template
&magine that we want to write a 4/n#tion to #ompare two val/es and indi#ate whether
the 4irst is less than$ e6/al to$ or greater than the se#ond.
&n pra#ti#e$ weFd want to de4ine several s/#h 4/n#tions$ ea#h o4 whi#h will #ompare
val/es o4 a given type.
O/r 4irst attempt might be to de4ine several overloaded 4/n#tionsH
// returns 0 if the values are equal, -1 if v1 is smaller, 1 if v2 is smaller
int compare(const string &v1, const string &v2)
{
if (v1 < v2) return -1
if (v2 < v1) return 1
return !
"
int compare(const doub#e &v1, const doub#e &v2)
{
if (v1 < v2) return -1
if (v2 < v1) return 1
return !
"
These 4/n#tions are nearly identi#alH The only di44eren#e between them is the type o4
their parameters.
The 4/n#tion body is the same in ea#h 4/n#tion.
Having to repeat the body o4 the 4/n#tion 4or ea#h type that we #ompare is tedio/s
and error!prone.
8ore importantly$ we need to 7now when we write the program all the types that we
might ever want to #ompare. This strategy #annot wor7 i4 we want to be able to /se
the 4/n#tion on types that o/r /sers might s/pply.
Lippman, Lajoie, Moo C++11
Standard Template Library Page ,+
0ather than de4ining a new 4/n#tion 4or ea#h type$ we #an de4ine a 4/n#tion
template!
- 4/n#tion template is a 4orm/la 4rom whi#h we #an generate type"specific
versions o4 that 4/n#tion.
The template version o4 #ompare loo7s li7e
Function Template Definition Example
temp#ate <t$pename %&
int compare(const % &v1, const % &v2)
{
if (v1 < v2) return -1
if (v2 < v1) return 1
return !
"
- template definition starts with the
keyword template 4ollowed by a
template parameter list$
whi#h is a #omma!separated list o4 one or more template parameters
bra#7eted by the less!than :L; and greater!than :M; to7ens.
O/r #ompare 4/n#tion de#lares one type parameter named T.
&nside #ompare$ we /se the name T to re4er to a type.
Nhi#h a#t/al type T represents is determined at #ompile time based on how #ompare
is /sed.
Standard Template Library Page ,1
Function templates Example
1. #include <iostream> // cin, cout, endl
2.
3. using std::cout;
4. using std::endl;
5. using std::string;
6.
7. template <tpename !>
". const !# ma$%const !# $, const !# &
'. (
1). i*% < $&
11. return $;
12. return ;
13. +
14.
15. int main%&
16. (
17.
1". // !,is -ill call ma$ <int> %. argument deduction&
1'. cout << ma$%3, 7& << endl;
2). // !,is -ill call ma$<dou.le> %. argument deduction&
21. cout << ma$%3.), 4.)& << endl;
22. // !,is tpe is am.iguous; e$plicitl instantiate ma$<dou.le>
23. cout << ma$<dou.le>%3, ".)& << endl;
24. // !,is tpe is c,aracter . e$plicit instantiation
25. cout << ma$<c,ar>%/0/, /1/& << endl;
26.
27.
2". return );
2'. +
&n 1* and ,1$ the template arg/ment T is a/tomati#ally ded/#ed by the #ompiler to be int
and do/ble$ respe#tively.
&n ,3$ #ase ded/#tion 4ails be#a/se the type o4 the parameters m/st in general e)a#tly mat#h
the template arg/ments.
This 4/n#tion template #an be instantiated with any #opy!#onstr/#tible type 4or whi#h the
e)pression :y L ); is valid.
For user"defined types# this implies that the less"than operator must be overloaded!
Standard Template Library Page ,,
Function Template ariations Example
// function template variations
#include <vector>
#include <iterator>
#include <iostream>
#include <cmath>
#include <string>
#include <utility>
#include <cstring>
using std::vector;
using std::cout;
using std::endl;
using std::string;
using std::iter_swap;
template <typename T>
void myReverse(T input!
"
typename T::iterator it;
typename T::iterator et;
for (it#input$%egin(!& et#input$end(!; it< et; it''& et((!
" iter_swap(it& et()!; *
return;
*
template <typename T>
void show+ontents(T input!
"
typename T::iterator it;
for (it#input$%egin(!; it ,# input$end(!; it''!
" cout << -it << . .; *
cout << endl;
*
int main(!
"
int /01 # ")& 2& 3& 4& 5*;
vector<int> 6y7ec(/& /'5!;
show+ontents(6y7ec!;
myReverse(6y7ec!;
show+ontents(6y7ec!;
string 6y8tring (.This is my +'' string.!;
show+ontents(6y8tring!;
myReverse(6y8tring!;
show+ontents(6y8tring!;
string str # .This is a + string.;
vector<char> data(str$%egin(!& str$end(!!;
show+ontents(data!;
myReverse(data!;
show+ontents(data!;
vector<string> fruit;
fruit$push_%ac9(.apple.!;
fruit$push_%ac9(.%anana.!;
fruit$push_%ac9(.orange.!;
fruit$push_%ac9(.straw%erry.!;
show+ontents((fruit!!;
myReverse(fruit!;
show+ontents((fruit!!;
*
Standard Template Library Page ,3
!lass templates
- #lass template provides a spe#i4i#ation 4or generating #lasses based on parameters.
Class templates are #ommonly /sed to implement #ontainers.
- #lass template is instantiated by passing a given set o4 types to it as template
arg/ments.
The C++ Standard Library #ontains many #lass templates$ in parti#/lar the #ontainers
adapted 4rom the Standard Template Library$ s/#h as ve#tor.
The basi# synta) 4or de#laring a templated #lass is as 4ollowsH
temp#ate <c#ass a_t$pe&
c#ass a_c#ass {'''"
The 7eyword C#lassC above simply means that the identi4ier a2type will stand 4or a datatype.
1oteH a2type is not a 7eyword? it is an identi4ier that d/ring the e)e#/tion o4 the program will
represent a single datatype. .or e)ample$ yo/ #o/ld$ when de4ining variables in the #lass$ /se the
4ollowing lineH
a_t$pe a_var
and when the programmer de4ines whi#h datatype Ca2typeC is to be when the program instantiates a
parti#/lar instan#e o4 a2#lass$ a2var will be o4 that type.
Nhen de#laring an instan#e o4 a templated #lass$ the synta) is as 4ollowsH
a_c#ass<int& an_e(amp#e_c#ass
Standard Template Library Page ,4
!lass Template Example
// class temlates
#include <iostream>
using namesace std;
temlate <class )>
class m!air {
) a& b;
ublic:
m!air () "irst& ) second)
{a="irst; b=second;3
) getma8 ();
3;
temlate <class )>
) m!air<)>::getma8 ()
{
) retval;
retval = a>bB a : b;
return retval;
3
int main () {
m!air <int> m!obCect (1--& DE);
cout << m!obCect.getma8();
return -;
3
Standard Template Library Page ,
introducing t"e vector template
// 2ect1.cpp 33 introducing t,e 2ector template 45
#include <iostream>
#include <string>
#include <2ector>
#de*ine 678 5
int main%&
(
using std::2ector;
using std::string;
using std::cin;
using std::cout;
using std::endl;
2ector<int> ratings%678&;
2ector<string> titles%678&;
cout << 9:ou -ill do e$actl as told. :ou -ill enter9
<< 678 << 9 .oo; titles and our ratings %)31)&.<n9;
int i;
*or %i = ); i < 678; i>>&
(
cout << 9?nter title #9 << i > 1 << 9: 9;
getline%cin,titles@iA&;
cout << 9?nter our rating %)31)&: 9;
cin >> ratings@iA;
cin.get%&;
+
cout << 9!,an; ou. :ou entered t,e *ollo-ing:<n9
<< 9Bating<tCoo;<n9;
*or %i = ); i < 678; i>>&
(
cout << ratings@iA << 9<t9 << titles@iA << endl;
+
return );
+
Standard Template Library Page ,"
STL components
!ontainers
Containers are ob>e#ts that #on#ept/ally #ontain other ob>e#ts.
They /se #ertain basi# properties o4 the ob>e#ts :ability to #opy$ et#.; b/t otherwise do
not depend on the type o4 ob>e#t they #ontain.
STL #ontainers may #ontain pointers to ob>e#ts$ tho/gh in this #ase yo/ will need to
do a little e)tra wor7.
ve#tors$ lists$ de6/es$ sets$ m/ltisets$ maps$ m/ltimaps$ 6/e/es$ sta#7s$ and priority
6/e/es$ are all provided.
Perhaps more importantly$
b/ilt!in #ontainers :C arrays; and
/ser!de4ined #ontainers
#an also be /sed as STL #ontainers?.
This is generally /se4/l when applying operations to the #ontainers$ e.g.$ sorting a
#ontainer.
Dsing /ser!de4ined types as STL #ontainers #an be a##omplished by satis4ying the
re6/irements listed in the STL #ontainer re6/irements de4inition.
&4 this is not 4easible$ yo/ #an de4ine an adaptor #lass that #hanges the inter4a#e to
satis4y the re6/irements.
-ll the types are JtemplatedJ$ o4 #o/rse$
so yo/ #an have a ve#tor o4 ints
or Nindows
or a ve#tor o4 ve#tor o4 sets o4 m/ltimaps o4 strings to St/dents.
Sweat$ #ompiler!writers$ sweatO ! 8a7e the #ompiler do the wor7.
Standard Template Library Page ,%
#ierarc"$
$e%uences
Contig/o/s blo#7s o4 ob>e#ts? yo/ #an insert elements at any point in the se6/en#e$
b/t the per4orman#e will depend on the type o4 se6/en#e and where yo/ are inserting.
&ectors
.ast insertion at end$ and allow random a##ess.
'ists
.ast insertion anywhere$ b/t provide only se6/ential a##ess.
(e%ues
.ast insertion at either end$ and allow random a##ess. 0estri#ted types$ s/#h as sta#7
and 6/e/e$ are b/ilt 4rom these /sing adaptors.
Standard Template Library Page ,'
$tacks and %ueues
Provide restri#ted versions o4 these types$ in whi#h some operations are not allowed.
Associative containers
-sso#iative #ontainers are a generaliEation o4 se6/en#es. Se6/en#es are inde)ed by
integers? asso#iative #ontainers #an be inde)ed by any type.
The most #ommon type to /se as a 7ey is a string? yo/ #an have a set o4 strings$ or a
map 4rom strings to employees$ and so 4orth.
&t is o4ten /se4/l to have other types as 7eys? 4or e)ample$ i4 & want to 7eep tra#7 o4
the names o4 all the Nidgets in an appli#ation$ & #o/ld /se a map 4rom Nidgets to
Strings.
$ets
Sets allow yo/ to add and delete elements$ 6/ery 4or membership$ and iterate thro/gh
the set.
)ultisets
8/ltisets are >/st li7e sets$ e)#ept that yo/ #an have several #opies o4 the same
element :these are o4ten #alled bags;.
)aps
8aps represent a mapping 4rom one type :the key type; to another type
:the value type;. Ko/ #an asso#iate a val/e with a 7ey$ or 4ind the val/e asso#iated
with a 7ey$ very e44i#iently? yo/ #an also iterate thro/gh all the 7eys.
)ultimaps
8/ltimaps are >/st li7e maps e)#ept that a 7ey #an be asso#iated with several val/es.
other #ontainersH
priority %ueue#
bit vector#
%ueue
Standard Template Library Page ,*
Example using container algorit"ms
Here is a program that generates a random perm/tation o4 the 4irst n integers$ where n
is spe#i4ied on the #ommand line.
#include <iostream.h>
#include <vector.h>
#include <algo.h>
#include <iterator.h>

main (int argc& char 4argv/0)
{
int n = atoi (argv/10); // argument chec%ing removed "or clarit!

vector<int> v;
"or (int i = -; i < n; i..) // aend integers - to n+1 to v
v.ush$bac% (i);

random$shu""le (v.begin()& v.end()); // shu""le
co! (v.begin()& v.end()& ostream$iterator<int> (cout& 12n1)); // rint
3
This program #reates an empty ve#tor and 4ills it with the integers 4rom + to n. &t
then sh/44les the ve#tor and prints it o/t.
Standard Template Library Page 3+

Container S$mmary Table
Simple !ontainers
*ontainer (escription
$imple *ontainers
pair
The pair container is a simple associative container consisting of a -*tuple of data
elements or objects, called ,first, and ,second,, in that fi"ed order. The .T/ ,pair, can be
assigned, copied and compared. The array of objects allocated in a map or hash0map
(described belo$) are of type ,pair, by default, $here all the ,first, elements act as the
uni'ue 1eys, each associated $ith their ,second, value objects.
$e%uences +Arrays , 'inked 'ists- " ordered collections
vector
a dynamic array, li1e C array (i.e., capable of random access) $ith the ability to resi(e
itself automatically $hen inserting or erasing an object. Inserting and removing an
element to2from bac1 of the vector at the end ta1es amorti(ed constant time. Inserting
and erasing at the beginning or in the middle is linear in time.
speciali(ation for type bool e"ists, $hich optimi(es for space by storing bool values as
bits.
list
a doubly*lin1ed list& elements are not stored in contiguous memory. 3pposite
performance from a vector. .lo$ loo1up and access (linear time), but once a position has
been found, 'uic1 insertion and deletion (constant time).
de'ue (double
ended 'ueue)
a vector $ith insertion2erase at the beginning or end in amorti(ed constant time,
ho$ever lac1ing some guarantees on iterator validity after altering the de'ue.
Standard Template Library Page 31
!ontainer Adaptors
*ontainer (escription
*ontainer adaptors
'ueue
4rovides #I#3 'ueue interface in terms of pus)/pop/front/back operations.
ny se'uence supporting operations front(), back(), pus)_back(),
and pop_front() can be used to instantiate 'ueue (e.g. list and de'ue).
priority0'ueue
4rovides priority 'ueue interface in terms of pus)/pop/top operations (the element $ith
the highest priority is on top).
ny random*access se'uence supporting operations front(), pus)_back(),
andpop_back() can be used to instantiate priority0'ueue (e.g. vector and de'ue).
5lements should additionally support comparison (to determine $hich element has a
higher priority and should be popped first).
stac1
4rovides /I#3 stac1 interface in terms of pus)/pop/top operations (the last*inserted
element is on top).
ny se'uence supporting operations back(), pus)_back(), and pop_back() can be used
to instantiate stac1 (e.g. vector, list, and de'ue).
Standard Template Library Page 3,
!ontainers % Associative and ot"er t$pes
*ontainer (escription
Associative containers " unordered collections
set
a mathematical set& inserting2erasing elements in a set does not invalidate iterators
pointing in the set. 4rovides set operations union, intersection, difference, symmetric
difference and test of inclusion. Type of data must implement comparison operator 6 or
custom comparator function must be specified. Implemented using a self*balancing
binary search tree.
multiset same as a set, but allo$s duplicate elements.
map
an associative array& allo$s mapping from one data item (a 1ey) to another (a value).
Type of 1ey must implement comparison operator 6 or custom comparator function must
be specified. Implemented using a self*balancing binary search tree.
multimap same as a map, but allo$s duplicate 1eys.
hash0set
hash0multiset
hash0map
hash0multima
p
similar to a set, multiset, map, or multimap, respectively, but implemented using a hash
table& 1eys are not ordered, but a hash function must e"ist for the 1ey type.
Thesecontainers are not part of the C++ .tandard /ibrary, but are included in .7I,s .T/
e"tensions, and are included in common libraries such as the 7%8 C++ /ibrary in
the00gnu0c"" namespace. These are scheduled to be added to the C++ standard as part
ofT)9, $ith the slightly different names of unordered0set,
unordered0multiset,unordered0map and unordered0multimap.
Other types of containers
bitset
stores series of bits similar to a fi"ed*si(ed vector of bools. Implements bit$ise
operations and lac1s iterators. %ot a .e'uence.
valarray
another C*li1e array li1e vector, but is designed for high speed numerics at the e"pense
of some programming ease and general purpose use. It has many features that ma1e it
ideally suited for use $ith vector processors in traditional vector supercomputers and
.I:; units in consumer*level scalar processors, and also ease vector mathematics
programming even in scalar computers.
Standard Template Library Page 33
#lgorithms
algorithm: Routines to find, count, sort, search, ... elements in container
classes
- large n/mber o4 algorithms to per4orm operations s/#h as sear#hing and sorting are provided in
the STL$
ea#h implemented to re6/ire a #ertain level o4 iterator :and there4ore will wor7 on any #ontainer
whi#h provides an inter4a#e by iterators;.
Algorit"ms librar$
C++
Algorithm library
The algorithms library defines functions for a variety of purposes (e.g.
searching, sorting, counting, manipulating) that operate on ranges of
elements. Note that a range is defined as @*irst, last& where last refers to
the element pastthe last element to inspect or modify.
Non-modif$ing se&uence operations
3e4ined in header <algorit,m>
all_of
any_of
none_of
:C++11;
:C++11;
:C++11;
#he#7s i4 a predi#ate is true 4or all$ any or none o4 the elements
in a range
:4/n#tion template;
for_each
applies a 4/n#tion to a range o4 elements
:4/n#tion template;
count
count_if
ret/rns the n/mber o4 elements satis4ying spe#i4i# #riteria
:4/n#tion template;
mismatch
4inds the 4irst position where two ranges di44er
:4/n#tion template;
equal
determines i4 two sets o4 elements are the same
:4/n#tion template;
find
find_if
find_if_not
:C++11;
4inds the 4irst element satis4ying spe#i4i# #riteria
:4/n#tion template;
find_end
4inds the last se6/en#e o4 elements in a #ertain range
:4/n#tion template;
find_first_of sear#hes 4or any one o4 a set o4 elements



Standard Template Library Page 34
:4/n#tion template;
adacent_find
4inds two identi#al :or some other relationship; items ad>a#ent to
ea#h other
:4/n#tion template;
search
sear#hes 4or a range o4 elements
:4/n#tion template;
search_n
sear#hes 4or a n/mber #onse#/tive #opies o4 an element in a
range
:4/n#tion template;
'odif$ing se&uence operations
3e4ined in header <algorit,m>
copy
copy_if
:C++11;
#opies a range o4 elements to a new lo#ation
:4/n#tion template;
copy_n
:C++11;
#opies a n/mber o4 elements to a new lo#ation
:4/n#tion template;
copy_backward
#opies a range o4 elements in ba#7wards order
:4/n#tion template;
move
:C++11;
moves a range o4 elements to a new lo#ation
:4/n#tion template;
move_backward
:C++11;
moves a range o4 elements to a new lo#ation in ba#7wards order
:4/n#tion template;
fill
assigns a range o4 elements a #ertain val/e
:4/n#tion template;
fill_n
assigns a val/e to a n/mber o4 elements
:4/n#tion template;
transform
applies a 4/n#tion to a range o4 elements
:4/n#tion template;
generate
saves the res/lt o4 a 4/n#tion in a range
:4/n#tion template;
generate_n
saves the res/lt o4 1 appli#ations o4 a 4/n#tion
:4/n#tion template;
remove
remove_if
removes elements satis4ying spe#i4i# #riteria
:4/n#tion template;
remove_copy
remove_copy_if
#opies a range o4 elements omitting those that satis4y spe#i4i#
#riteria
:4/n#tion template;
replace
replace_if
repla#es all val/es satis4ying spe#i4i# #riteria with another val/e
:4/n#tion template;
replace_copy
replace_copy_if
#opies a range$ repla#ing elements satis4ying spe#i4i# #riteria
with another val/e
Standard Template Library Page 3
:4/n#tion template;
swap
swaps the val/es o4 two ob>e#ts
:4/n#tion template;
swap_ranges
swaps two ranges o4 elements
:4/n#tion template;
iter_swap
swaps the elements pointed to by two iterators
:4/n#tion template;
reverse
reverses the order elements in a range
:4/n#tion template;
reverse_copy
#reates a #opy o4 a range that is reversed
:4/n#tion template;
rotate
rotates the order o4 elements in a range
:4/n#tion template;
rotate_copy
#opies and rotate a range o4 elements
:4/n#tion template;
random_shuffle
shuffle

:C++11;
randomly re!orders elements in a range
:4/n#tion template;
unique
removes #onse#/tive d/pli#ate elements in a range
:4/n#tion template;
unique_copy
#reates a #opy o4 some range o4 elements that #ontains no
#onse#/tive d/pli#ates
:4/n#tion template;
Partitioning operations
3e4ined in header <algorit,m>
is_partitioned
:C++11;
determines i4 the range is partitioned by the given predi#ate
:4/n#tion template;
partition
divides a range o4 elements into two gro/ps
:4/n#tion template;
partition_copy
:C++11;
#opies a range dividing the elements into two gro/ps
:4/n#tion template;
stable_partition
divides elements into two gro/ps while preserving their relative
order
:4/n#tion template;
partition_point
:C++11;
lo#ates the partition point o4 a partitioned range
:4/n#tion template;
Sorting operations (on sorted ranges)
3e4ined in header <algorit,m>
is_sorted
:C++11;
#he#7s whether a range is sorted into as#ending order
:4/n#tion template;
Standard Template Library Page 3"
is_sorted_until
:C++11;
4inds the largest sorted s/brange
:4/n#tion template;
sort
sorts a range into as#ending order
:4/n#tion template;
partial_sort
sorts the 4irst 1 elements o4 a range
:4/n#tion template;
partial_sort_copy
#opies and partially sorts a range o4 elements
:4/n#tion template;
stable_sort
sorts a range o4 elements while preserving order between e6/al
elements
:4/n#tion template;
nth_element
partially sorts the given range ma7ing s/re that it is partitioned
by the given element
:4/n#tion template;
*inar$ searc" operations (on sorted ranges)
3e4ined in header <algorit,m>
lower_bound
ret/rns an iterator to the 4irst element not less than the given
val/e
:4/n#tion template;
upper_bound
ret/rns an iterator to the 4irst element greater than a #ertain
val/e
:4/n#tion template;
binary_search
determines i4 an element e)ists in a #ertain range
:4/n#tion template;
equal_range
ret/rns range o4 elements mat#hing a spe#i4i# 7ey
:4/n#tion template;
Set operations (on sorted ranges)
3e4ined in header <algorit,m>
merge
merges two sorted ranges
:4/n#tion template;
inplace_merge
merges two ordered ranges in!pla#e
:4/n#tion template;
includes
ret/rns tr/e i4 one set is a s/bset o4 another
:4/n#tion template;
set_difference
#omp/tes the di44eren#e between two sets
:4/n#tion template;
set_intersection
#omp/tes the interse#tion o4 two sets
:4/n#tion template;
set_symmetric_differen
ce
#omp/tes the symmetri# di44eren#e between two sets
:4/n#tion template;
Standard Template Library Page 3%
set_union
#omp/tes the /nion o4 two sets
:4/n#tion template;
#eap operations
3e4ined in header <algorit,m>
is_heap
#he#7s i4 the given range is a heap
:4/n#tion template;
is_heap_until
:C++11;
4inds the largest s/brange that is heap
:4/n#tion template;
make_heap
#reates a heap o/t o4 a range o4 elements
:4/n#tion template;
push_heap
adds an element to a heap
:4/n#tion template;
pop_heap
removes the largest element 4rom a heap
:4/n#tion template;
sort_heap
t/rns a heap into a sorted range o4 elements
:4/n#tion template;
'inimum+maximum operations
3e4ined in header <algorit,m>
max
ret/rns the larger o4 two elements
:4/n#tion template;
max_element
ret/rns the largest element in a range
:4/n#tion template;
min
ret/rns the smaller o4 two elements
:4/n#tion template;
min_element
ret/rns the smallest element in a range
:4/n#tion template;
minmax
:C++11;
ret/rns the larger and the smaller o4 two elements
:4/n#tion template;
minmax_element
:C++11;
ret/rns the smallest and the largest element in a range
:4/n#tion template;
lexicographical_compar
e
ret/rns tr/e i4 one range is le)i#ographi#ally less than another
:4/n#tion template;
is_permutation
:C++11;
determines i4 a se6/en#e is a perm/tation o4 another se6/en#e
:4/n#tion template;
next_permutation
generates the ne)t greater le)i#ographi# perm/tation o4 a range
o4 elements
:4/n#tion template;
prev_permutation
generates the ne)t smaller le)i#ographi# perm/tation o4 a range
o4 elements
:4/n#tion template;
Standard Template Library Page 3'
Numeric operations
3e4ined in header <numeric>
iota
:C++11;
4ills a range with s/##essive in#rements o4 the starting val/e
:4/n#tion template;
accumulate
s/ms /p a range o4 elements
:4/n#tion template;
inner_product
#omp/tes the inner prod/#t o4 two ranges o4 elements
:4/n#tion template;
adacent_difference
#omp/tes the di44eren#es between ad>a#ent elements in a range
:4/n#tion template;
partial_sum
#omp/tes the partial s/m o4 a range o4 elements
:4/n#tion template;
! librar$
3e4ined in header <cstdli.>
qsort
sorts a range o4 elements with /nspe#i4ied type
:4/n#tion;
bsearch
sear#hes an array 4or an element o4 /nspe#i4ied type
:4/n#tion;
Standard Template Library Page 3*
%$nctors
The STL in#l/des #lasses that overload the 4/n#tion operator :operator:;;
They are /se4/l 4or 7eeping and retrieving state in4ormation in 4/n#tions passed into other
4/n#tions.
./n#tion ob>e#ts :a7a J4/n#torsJ;. ./n#tors are ob>e#ts that #an be treated as tho/gh they are a
4/n#tion or 4/n#tion pointer!!yo/ #o/ld write #ode that loo7s li7e thisH
1
2
my!unctor"lass functor$
functor% &' (' ) *$
This #ode wor7s be#a/se C++ allows yo/ to overload operator:;$ the J4/n#tion #allJ operator. The
4/n#tion #all operator #an ta7e any n/mber o4 arg/ments o4 any types and ret/rn anything it wishes
to. :&tCs probably the most 4le)ible operator that #an be overloaded;
httpH==www.#programming.#om=t/torial=4/n#tors!4/n#tion!ob>e#ts!in!#++.html
#include <iostream>

class myFunctorClass
{
public:
myFunctorClass (int x) : _x( x ) {}
int operator() (int y) { return _x + y; } <<<<<<<<<<<
pri!ate:
int _x;
};

int main()
{
myFunctorClass addFi!e( " );
std::cout << addFi!e( # );

return $;
}
Standard Template Library Page 4+
C++ Standard Library
"++ +tandard
,ibrary
ios
iostream
iomanip
*stream
sstream
Standard Template Library Page 41
!,, Standard -ibrar$
+tandard
-emplate
,ibrary
.,, wx/idgets "lasses
2ector
deDue
list
map
set
stac;
Dueue
.itset
algorit,m
*unctional
iterator
5$Eector
-$Fist
-$4as,8ap
-$4as,Get
-$Gtac;

Вам также может понравиться