the standard template library

28
The Standard The Standard Template Library Template Library

Upload: ludlow

Post on 05-Jan-2016

32 views

Category:

Documents


1 download

DESCRIPTION

The Standard Template Library. Books on standard C++ library. Nicolai M. Josuttis: C++ Standard Library: A tutorial and Reference, 1st, Pearson 1999, examples: http://www.josuttis.com/libbook/examples.zip - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: The Standard Template Library

The Standard Template The Standard Template LibraryLibrary

Page 2: The Standard Template Library

Books on standard C++ libraryBooks on standard C++ library

Nicolai M. Josuttis: C++ Standard Library: A Nicolai M. Josuttis: C++ Standard Library: A tutorial and Reference, 1st, Pearson 1999,tutorial and Reference, 1st, Pearson 1999,

examples: examples: http://www.josuttis.com/libbook/examples.ziphttp://www.josuttis.com/libbook/examples.zip (Polish: Nicolai M. Josuttis: C++ Biblioteka (Polish: Nicolai M. Josuttis: C++ Biblioteka

standardowa Podręcznik Programisty, Helion 2003, standardowa Podręcznik Programisty, Helion 2003, examples: examples: ftp://ftp.helion.pl/przyklady/cpbspp.zipftp://ftp.helion.pl/przyklady/cpbspp.zip))

(Grębosz J.: Pasja C++, RM, W-wa)(Grębosz J.: Pasja C++, RM, W-wa) Other (mentioned on Lecture Nr 1)Other (mentioned on Lecture Nr 1)

Page 3: The Standard Template Library

Standard library of C++ languageStandard library of C++ language

STLSTL(The main part of standard library of C++ language)(The main part of standard library of C++ language)

Stream classesStream classes String classesString classes

(library defined within std namespace)(library defined within std namespace)

Page 4: The Standard Template Library

Standard Template LibraryStandard Template Library Main elementsMain elements

Generic data Generic data containerscontainers (lists, vectors, etc.) (lists, vectors, etc.) IteratorsIterators for browsing containers and providing an interface to for browsing containers and providing an interface to

containers for algorithmscontainers for algorithms AlgorithmsAlgorithms operating on containers operating on containers Other (to be discussed later ...)Other (to be discussed later ...)

It is a It is a templatetemplate library! library! Data is generally separated from methods (where the OOP Data is generally separated from methods (where the OOP

idea has gone?)idea has gone?) Designed for high-level programmingDesigned for high-level programming Designed for efficient programmingDesigned for efficient programming

Page 5: The Standard Template Library

BTW: algorithm’s complexity orderBTW: algorithm’s complexity order

O-notationO-notation

find element in sorted array:find element in sorted array: O(logO(log22(n))(n)) find element in unsorted array: find element in unsorted array: O(n)O(n) quicksort:quicksort: O(n O(n ·· log log22(n))(n)) bubblesort:bubblesort: O(nO(n22))

Page 6: The Standard Template Library

ContainersContainers

SequentialSequential vector (dynamic table)vector (dynamic table) dequeue (double ende queue, using dynamic table)dequeue (double ende queue, using dynamic table) list (double linked one)list (double linked one) (arrays and strings not STL containers, but operable by (arrays and strings not STL containers, but operable by

STL algorithms)STL algorithms)

AssociativeAssociative set (using binary tree)set (using binary tree) multisetmultiset map, multimapmap, multimap

Page 7: The Standard Template Library

ContainersContainers

vector vector implemented as a dynamic tableimplemented as a dynamic table

fast push_back()fast push_back() fast operator[]fast operator[]

slow insert()slow insert()

Page 8: The Standard Template Library

ContainersContainers

deque deque implemented using dynamic tableimplemented using dynamic table

fast push_back() fast push_back() (here vector may be faster)(here vector may be faster) fast push_front() fast push_front() (not in vector template)(not in vector template) fast operator[]fast operator[]

slow insert()slow insert()

Page 9: The Standard Template Library

ContainersContainers

list list implemented using double linked listimplemented using double linked list

fast push_back()fast push_back() fast push_front()fast push_front() fast insert()fast insert()

no operator[]no operator[]

Page 10: The Standard Template Library

IteratorsIterators Iterators behave like regular pointers ...Iterators behave like regular pointers ...

* * ->-> ++++ ---- ==== !=!= == (vector, deq: -, <, >, +(int) )(vector, deq: -, <, >, +(int) )

But work for all the containers!But work for all the containers! container.begin()container.begin() // return iterator of first elem.// return iterator of first elem. container.end()container.end() // return iterator next to last // return iterator next to last

elem.elem.

example: list2.cppexample: list2.cpp

Page 11: The Standard Template Library

ContainersContainers set set

implemented using binary treeimplemented using binary tree sorted at insert (by default using operator<() )sorted at insert (by default using operator<() ) equivalent to math. setsequivalent to math. sets

find() methodfind() method

fast insert()fast insert()

no push_back()no push_back() no push_front()no push_front() no operator[]no operator[]

Page 12: The Standard Template Library

ContainersContainers

multiset multiset set that allows repetitions of the same valueset that allows repetitions of the same value ordering within group of elements of the same ordering within group of elements of the same

value is undefinedvalue is undefined

Page 13: The Standard Template Library

ContainersContainers

multimapmultimap multiset of pairs: key, val – use make_pair() multiset of pairs: key, val – use make_pair()

Page 14: The Standard Template Library

ContainersContainers

mapmap set of pairs: key, val – use make_pair() set of pairs: key, val – use make_pair()

For map onlyFor map only: operator[key](): operator[key]() index by value (associative array) index by value (associative array)

Page 15: The Standard Template Library

STL AlgorithmsSTL Algorithms

Operate on containers using iterator interfaceOperate on containers using iterator interface generic, but not as fast as containers’ methodsgeneric, but not as fast as containers’ methods slow on some combinations of algorithm/containerslow on some combinations of algorithm/container may operate on various containers at the same timemay operate on various containers at the same time

Only elementary, simple algorithmsOnly elementary, simple algorithms parametrizable by different iteratorsparametrizable by different iterators parametrizable by function objects and adaptors parametrizable by function objects and adaptors

Not very intuitive (an euphemism)Not very intuitive (an euphemism)

Page 16: The Standard Template Library

STL AlgorithmsSTL Algorithms Example: algo1.cppExample: algo1.cpp

min_elementmin_element // operator<()// operator<() max_elementmax_element // operator<()// operator<() sortsort // operator<()// operator<() findfind // operator==()// operator==() reversereverse // operator=()// operator=()

min_element (coll.begin(), coll.end())min_element (coll.begin(), coll.end()) range is range is [[ coll.begin(), coll.end() coll.begin(), coll.end() )) ((example: find1.cppexample: find1.cpp)) proper range definition is a programmer’s responsibilityproper range definition is a programmer’s responsibility range end should be attainable by ++’ing of startrange end should be attainable by ++’ing of start what if we’re not sure of what is beginning, what is end?what if we’re not sure of what is beginning, what is end?

Page 17: The Standard Template Library

STL AlgorithmsSTL Algorithms

copy (coll1.begin(), coll1.end(), coll2.begin()); copy (coll1.begin(), coll1.end(), coll2.begin()); end of range given only for first rangeend of range given only for first range sizes of ranges must suffice sizes of ranges must suffice

algorithm does elementary copy onlyalgorithm does elementary copy only doesn’t check destination size doesn’t check destination size

(iteartors are intreface to elements, not to whole (iteartors are intreface to elements, not to whole collection)collection)

proper collection size is a programmer’s responsibility proper collection size is a programmer’s responsibility ((example: copy2.cppexample: copy2.cpp))

setting initial collection size is easy for some setting initial collection size is easy for some (sequential) container classes(sequential) container classes

Page 18: The Standard Template Library

STL IteratorsSTL Iterators sizes of ranges must suffice, or ...sizes of ranges must suffice, or ... copy (coll1.begin(), coll1.end(),copy (coll1.begin(), coll1.end(),

inserter(inserter(coll2coll2, coll2.begin(), coll2.begin())) ); );

... or use inserter iterators ;) ... or use inserter iterators ;) ((example: example: copy3.cppcopy3.cpp)) inserter for all containers, all can insert()inserter for all containers, all can insert()

inserts before specified location inserts before specified location for associative containers location is a hint onlyfor associative containers location is a hint only

back_inserter for containers that can push_back()back_inserter for containers that can push_back() front_inserter for containers that can push_front()front_inserter for containers that can push_front()

Page 19: The Standard Template Library

STL IteratorsSTL Iterators

stream iteratorsstream iterators behave like regular onesbehave like regular ones

have interface of regular oneshave interface of regular ones operate on i/o streams operate on i/o streams (example: ioiter1.cpp)(example: ioiter1.cpp)

istream_iterator<string>(cin) istream_iterator<string>(cin) ++iter for stream>>temp, *iter for retrieving temp++iter for stream>>temp, *iter for retrieving temp

istream_iterator<string>()istream_iterator<string>() end of stream iteratorend of stream iterator

Page 20: The Standard Template Library

STL IteratorsSTL Iterators

reverse iteratorsreverse iterators have interface of regular oneshave interface of regular ones reverse regular behaviour reverse regular behaviour (example: rter1.cpp)(example: rter1.cpp)

container.rbegin() is actually last element container.rbegin() is actually last element (not the one (not the one afterafter last) last)

container.rend() is actually element before first one!container.rend() is actually element before first one! ++ is --, -- is ++, etc. ++ is --, -- is ++, etc.

Page 21: The Standard Template Library

STL AlgorithmsSTL Algorithms removing elements from container removing elements from container

remove(...) algorithmremove(...) algorithm actually doesn’t remove container contents actually doesn’t remove container contents ((example: example:

remove1.cppremove1.cpp)) elementary operation of moving elementselementary operation of moving elements doesn’t know the container, knows elementsdoesn’t know the container, knows elements doesn’t work for associative containersdoesn’t work for associative containers returns new end of range (next to last)returns new end of range (next to last)

use method erase(...) to get rid of elements use method erase(...) to get rid of elements ((example: remove2.cppexample: remove2.cpp))

many versionsmany versions works for associative containers works for associative containers ((example: remove3.cppexample: remove3.cpp))

Page 22: The Standard Template Library

Extending STLExtending STL

programmer is allowed (and encouraged) to programmer is allowed (and encouraged) to extend STL functionalityextend STL functionality create new templates, or just classes/functionscreate new templates, or just classes/functions example: print.hppexample: print.hpp

typename keyword denotes argument’s type/classtypename keyword denotes argument’s type/class as opposed to „mutable” it is usefullas opposed to „mutable” it is usefull

Page 23: The Standard Template Library

Function as algorithm argumentFunction as algorithm argument

single argument functions single argument functions examples: foreach1.cpp, transform1.cppexamples: foreach1.cpp, transform1.cpp

predicates predicates single argument and bool result single argument and bool result

((example: prime1.cppexample: prime1.cpp)) two arguments and bool result two arguments and bool result

((example: sort1.cppexample: sort1.cpp))

Page 24: The Standard Template Library

Function object as algorithm Function object as algorithm argumentargument

function objectsfunction objects behave like functions, but using operator()() behave like functions, but using operator()() example: foreach2.cppexample: foreach2.cpp are objectsare objects

easily optimizable by compiler easily optimizable by compiler may have class member variables, „internal state” may have class member variables, „internal state”

passed by the constructor argument passed by the constructor argument ((example: example: add1.cppadd1.cpp))

we may have many function objects of the same classwe may have many function objects of the same class

Page 25: The Standard Template Library

Function object as algorithm Function object as algorithm argumentargument

predefined function object templatespredefined function object templates less<>, greater <>less<>, greater <>

set<int> s;set<int> s; defaults to defaults to set<int, less<int> > s;set<int, less<int> > s;

we may also:we may also: set<int, greater<int> > s;set<int, greater<int> > s;

negate<>, multiply<> negate<>, multiply<> // use in transform(...) algorithm// use in transform(...) algorithm

Page 26: The Standard Template Library

Function adaptorsFunction adaptors

define special cases of function usedefine special cases of function use adapt function, when different interface (i.e. adapt function, when different interface (i.e.

argument list) is requiredargument list) is required bind2nd(less<int>(),50)bind2nd(less<int>(),50) ((example: fo1.cppexample: fo1.cpp))

creates default second argumentcreates default second argument

Page 27: The Standard Template Library

Container elementsContainer elements

interface required alwaysinterface required always copy constructorcopy constructor assignment operatorassignment operator destructordestructor

interface required sometimesinterface required sometimes default constructordefault constructor equality operator ==equality operator == comparison operator <comparison operator <

Page 28: The Standard Template Library

STL, errors and exceptionsSTL, errors and exceptions

aimed at maximizing speedaimed at maximizing speed in case of improper use (*end()=something) behaviour is in case of improper use (*end()=something) behaviour is

undefined, let’s hope it crashesundefined, let’s hope it crashes be carefull with iterators and rangesbe carefull with iterators and ranges only minimal chcecks are done (bad_alloc exception)only minimal chcecks are done (bad_alloc exception)

there is a debug version of the librarythere is a debug version of the library use it!use it!

some methods of some containers are transaction-safesome methods of some containers are transaction-safe some are not!some are not! check the reference!check the reference!