introduction to the iso c++ standard template library (stl) jean-paul rigault professor, École...
TRANSCRIPT
Introduction to the ISO C++ Standard Template Library
(STL)
Jean-Paul RigaultProfessor, École supérieure en sciences informatiques
(ESSI)University of Nice Sophia Antipolis
Version 1.1 (January 2002)
Version 1.1 (January 2002) C++ STL 2
Purpose of the STL
• Language run-time support• Implementation characteristics
– Implementation limits– Standard function with a machine-
dependent optimal implementation
• Non primitive, yet portable objects• Extensibility• Foundation for other libraries
Version 1.1 (January 2002) C++ STL 3
Implementation Constraints
• Usable directly and easily
• Efficient• Neutral policy• Primitive• Complete
• Compatible with base types
• Type-safe• Support for all
programming styles
• Extensible
Version 1.1 (January 2002) C++ STL 4
Organization of the C++ STL
• Namespace std• Header files
– Recover ANSI C header files(<cXXXX> <XXXX.h>)
• Library elementsContainers, iterators, algorithms, general utilities, diagnostics, strings, input-output, localization, basic run-time support, (numerical elements)
Version 1.1 (January 2002) C++ STL 5
Containers
• Homogeneous contents• Homogeneous interface
– Common member-functions– Iterators
• Specific member-functions• Parametrized memory allocation
scheme (template parameter)– default allocator : allocator<T>
Version 1.1 (January 2002) C++ STL 6
Containers : Different Types
Basic Containersvector<T> vector with automatic (re)allocationlist<T> doubly linked sequence (list)dequeue<T> sequence with optimized indexing
Container adaptersstack<T> LIFOqueue<T> FIFOpriority_queue<T> queue with priority (operator <)
Associative containersmap<K, T> associative array without duplicate (K is the key)multimap<K, T> associative array with duplicate (K is the key)set<K> set (without duplicate) of Kmultiset<K> set with duplicate (i.e., bag) of K
Version 1.1 (January 2002) C++ STL 7
Containers : Iterators (1)
• Model : sequence and extended pointer
*p
begin() end()iteratorp
++--
list<int> L;for (int i = 0; i < N; i++) L.push_front(i);list<int>::const_iterator it;for (it = L.begin(); it != L.end(); it++)
cout << *it << ' ';
rend() rbegin()
Version 1.1 (January 2002) C++ STL 8
Containers : Iterators (2)
• Reverse iteration– Use a reverse iteratorlist<int>::const_reverse_iterator rit;for (rit = L.rbegin(); rit != L.rend(); rit++)
cout << *rit << ' ';
• Non const iterator– Allow modification of container elementslist<int>::reverse_iterator rit;
for (rit = L.rbegin(); rit != L.rend(); rit++)*rit = 10;
Version 1.1 (January 2002) C++ STL 9
Containers : Iterators (3)
• Using iterators as interval bounds
list<int> L;list<int>::iterator it;int n;...for (n = 0, it = L.begin();
(it = find(it, L.end(), 3) != L.end(); it++){
n++;}
– Iterator intervals always include left bound and exclude right one ([ … [)
Version 1.1 (January 2002) C++ STL 10
Containers: Common Characteristics
• Member-typesvalue_type type of valueiterator ~ value_type*
const_iterator ~ const value_type*
reverse_iterator ~ value_type*
const_reverse_iterator ~ const value_type*
reference ~ value_type&
const_reference ~ const value_type&
Version 1.1 (January 2002) C++ STL 11
Containers : Common Characteristics
Common Member-Functions (1)• Iteration
begin() “Point” to first elementend() “Point” to just after last elementrbegin() “Point” to first element in reverse orderrend() “Point” to just after last element in reverse order
• Access to contentsfront() Reference to first elementlast() Reference to last element[] Indexing without bound checking (N/A for lists)at() Indexing with bound checking (N/A for lists)
Version 1.1 (January 2002) C++ STL 12
Containers : Common Characteristics
Common Member-Functions (2)• Operations on lists, stacks, and
queuespush_back() Append (add after last)pop_back() Remove last element and return its valuepush_front() Prepend (add before first)pop_front() Remove first element and return its value
• Operations on list (sequence)insert() Insert before an elementerase() Remove an elementclear() Remove all elements
Version 1.1 (January 2002) C++ STL 13
Containers : Common Characteristics
Common Member-Functions (3)• Miscellaneous operations
size() Number of elementsempty() Is the container empty ?max_size() Maximum possible sizeswap() Swap two elements== != < Comparisons
• Assignmentsassign(n) Assign n elements (to their default value)assign(n, x) Assign n copies of xassign(first, last) Assign all elements between iterators
first and last to default value = Ordinary (copy) assignment
Version 1.1 (January 2002) C++ STL 14
Containers : Common Characteristics
Common Member-Functions (4)• Construction and destruction
container() Empty containercontainer(n) Container with n elements
(initialized to their default value)container(n, x) Container with n copies of
element xcontainer(first, last) Container with elements copied
from interval between iterators first et last
container(other_container) Copy of container~container() Destructor
Version 1.1 (January 2002) C++ STL 15
Containers : Remarks (1)
• Constraints on the elements (value_type)– Default constructor
• Define the "zero" of the type– Copy operations– For ordered containers, “less than” operator
(<) • If no equality operator, “less than” is used : a == b !(a < b) && !(b < a)
• Vectors– No arithmetics (see valarray)– Specialization vector<bool> is defined
Version 1.1 (January 2002) C++ STL 16
Containers : Remarks (2)
• Associative containers (maps and sets) specific member functionsoperator[](k) Access to element with key kfind(k) Find element with key klower_bound(k) The smallest element with key kupper_bound(k) The largest element with key k
equal_range(k) Interval of elements with key k
Version 1.1 (January 2002) C++ STL 17
Containers : Remarks (3)
•Map– Indexing allocates the element if not
already there– Map iterators point to pairs (pair<K, T>)
map<string, char> M;M["hello"] = 'A';map<string, char>::iterator it;it = M.find("hello");// *it is a pair<string, char>cout << it->first << ' ' << it->second;
Version 1.1 (January 2002) C++ STL 18
Containers : Remarks (4)
• Multimaps, sets, multisets– Indexing allocates the element if not
already there
• Sets– set<K> is a sort of map<K, K>– No set operation (union, intersection…) is
defined in set<K>• However, see Set Algorithms further
Version 1.1 (January 2002) C++ STL 19
Containers : Operation Complexity
Indexing [], at()
List operations
Operations on the head of
a sequence
Operations on the tail of a sequence
vector list dequeue
O(1) O(1)
O(n)+ O(1) O(n)
O(1) O(1)
O(1)+ O(1) O(1)
stack queue priority_queue
O(n) O(n) O(log n)
O(1) O(log n)
O(1) O(1)
map multimap set multiset
O(log n)+ O(log n)+
O(log n)+ O(log n)+ O(log n)+ O(log n)+
string array valarray bitset
O(1) O(1) O(1) O(1)
O(n)+ O(n)+ O(1)+
Version 1.1 (January 2002) C++ STL 20
Algorithms
• About sixty predefined algorithms– Non-modifying operations on sequences– Modifying operations on sequences– Sort and merge operations on sequences– Set operations– Miscellaneous operations
• Header file <algorithm>
Version 1.1 (January 2002) C++ STL 21
Algorithms on Sequences/Sets (1)
• Use iterators – to specify their range of action– to retrieve the result
list<int> L;
...
list<int>::iterator it = find(L.begin(), L.end(), 7);
Version 1.1 (January 2002) C++ STL 22
Algorithms on Sequences/Sets (2)
• May have parameters indicating an action to perform on each element of the sequence– either selecting elements– or modifying elements
list<int> L;
...
list<int>::iterator it = find(L.begin(), L.end(), 7);
Version 1.1 (January 2002) C++ STL 23
Algorithms on Sequences/Sets (3)
• Sequence filteringbool is_gt_4(int i) {
return i > 4;}...list<int> L;int n =
count_if(L.begin(), L.end(), is_gt_4);
Version 1.1 (January 2002) C++ STL 24
Algorithms on Sequences/Sets (4)
• Transforming a sequenceint length(string s) {
return s.size();}...list<string> LS(10, ″hello ″);vector<int> VI(LS.size());...transform(LS.begin(), LS.end(), VI.begin(), length);
Version 1.1 (January 2002) C++ STL 25
Algorithms on Sequences/Sets Function-Objects (1)
• Algorithms for_each, find_if, count_if... are templates functions
template <typename InputIterator, typename Predicate>InputIterator find_if(InputIterator first, InputIterator last, Predicate pred){
InputIterator it; for (it = first; it != last && !pred(*it); it++){}return it;
}
Version 1.1 (January 2002) C++ STL 26
Algorithms on Sequences/Sets Function-Objects (2)
• Predicate denotes a type– either a pointer to a function
(such as is_gt_4)– or a class defining operator()
• In all cases the signature of the “function” should be something likebool pred(InputIterator::value_type)
Version 1.1 (January 2002) C++ STL 27
Algorithms on Sequences/Sets Function-Objects (3)
• A function-object is an instance of a class defining operator()list<int> L;class is_gt_4 {public:
bool operator() (int i) {return i > 4;}};…is_gt_4 criter; // define an objectint n =
count_if(L.begin(), L.end(), criter);
Version 1.1 (January 2002) C++ STL 28
Algorithms on Sequences/SetsFunctionals (1)
class Figure {
public:
...
void draw() const;
void rotate(int angle);
};
list<Figure> LF;
...
for_each(LF.begin(), LF.end(), &Figure::draw);
Error !
Version 1.1 (January 2002) C++ STL 29
Algorithms on Sequences/SetsFunctionals (2)
for_each(LF.begin(), LF.end(),
mem_fun_ref(&Figure::draw));
– mem_fun_ref is an example of a functional• here it turns a pointer to a member-function
(without parameter) into a function-object
– Functionals are defined in <functional>• several “special effects” : handling pointers
and references, parameters passing…
Version 1.1 (January 2002) C++ STL 30
Algorithms on Sequences/SetsFunctionals (3)
• Predefined function-objectsnegate<type>(p) -- pplus<type>(p1, p2) p1 + p2
and minus, multiplies, divides, modulusequal_to<type>(p1, p2) p1 == p2
and not_equal_toless<type>(p1, p2) p1 < p2
and greater, less_equal, greater_equallogical_not<type>(p) !p
logical_and<type>(p1, p2) p1 && p2
and logical_or
Version 1.1 (January 2002) C++ STL 31
Algorithms on Sequences/SetsFunctionals (4)
• Function adapters for function-objectsit = find_if(l.begin(), l.end(),
bind2nd(greater<int>(), 35));– bind1st and bind2nd bind respectively the
first and the second parameter of a 2 parameters function-object
– not1 and not2 return the logical_not of a function-object returning a boolean (respectively with 1 or 2 parameters)
Version 1.1 (January 2002) C++ STL 32
Algorithms on Sequences/SetsFunctionals (5)
• Function adapter for ordinary functions– Function adapters can only be applied to
function-objects, not to pointers to ordinary function
– ptr_fun turns a pointer to a regular function into a function-object
– As a consequence all the function-objects adapters can be applied to the resulting function-object
Version 1.1 (January 2002) C++ STL 33
Algorithms on Sequences/SetsFunctionals (6)
• Function adapters for member-functions– mem_fun_ref(pm)
• Turn a pointer to a member-function (pm) into a function-objet: the current object is passed by reference
– mem_fun(pm)• Turn a pointer to a member-function (pm) into a
function-objet: the current object is passed as a pointer
• Many other functionals and function-objects (see the STL documentation)
Version 1.1 (January 2002) C++ STL 34
Algorithms on Sequences/SetsFunctionals (7)
• Composing function-object adapterslist<char *> ls;…it = find_if(ls.begin(), ls.end(),
bind2nd(ptr_fun(strcmp), ″hello″));
vector<Figure *> vfp;…for_each(vfp.begin(), vfp.end(),
bind2nd(mem_fun(&Figure::rotate), PI/2));
Version 1.1 (January 2002) C++ STL 35
AlgorithmsNon-Modifying Operations on
Sequencesfor_each() Apply a function to each elementfind() find_if() Find an element in a sequence with some
value (resp. satisfying some condition)find_first_of() Find an element from a sequence in another
sequenceadjacent_find() Find consecutive duplicate elementscount() count_if() Count all occurrences of an element with a
given value (resp. satisfying some condition)mismatch() Find all elements differing between two
sequencesequal() Check sequence equalitysearch() Find a sub-sequence within another sequencefind_end() Find the last occurrence of a sub-sequence
within another sequencesearch_n() Find the nth occurrence of a sub-sequence
within another sequence
Version 1.1 (January 2002) C++ STL 36
AlgorithmsModifying Operations on
Sequences (1)transform() Apply a function to all elementscopy() copy_backward() Copy a sequence
from the beginning or the endswap() iter_swap() Swap two elements pointed to by iteratorsswap_ranges() Swap elements between two sequencesreplace() replace_if() Replace elements
with a given value or satisfying some condition
replace_copy() replace_copy_if() Copy a sequence, replacing elements with a given value or satisfying some condition
fill() fill_n() Replace (first n) elements by some valuegenerate() generate_n() Replace (first n)
elements with a given value by the result of some operation
Version 1.1 (January 2002) C++ STL 37
AlgorithmsModifying Operations on
Sequences (2)remove() remove_if()Remove elements with a given value or
satisfying some conditionremove_copy() remove_copy_if() Copy a sequence, removing
elements with a given value or satisfying some condition
unique() Detect and isolate consecutive duplicatesunique_copy() Copy a sequence , removing consecutive
duplicatesreverse() reverse_copy() Copy a sequence in reverse orderrotate() rotate_copy() Copy a
sequence together with circular permutationrandom_shuffle() Permute elements according to an uniform
distribution
Version 1.1 (January 2002) C++ STL 38
AlgorithmsModifying Operations on
Sequences (3)• The modifying algorithms never
modify the number of elements in the container– They may modify the order of the elements– And also the value of the elements themselves
dequeue<double> dq(10, 3.14); // 10 elementslist<double> ld; // empty by default…copy(dq.begin(), dq.end(), ld.begin());
// likely to crash!!
Version 1.1 (January 2002) C++ STL 39
AlgorithmsModifying Operations on
Sequences (4)• Insert iterators
– Special iterators for which ++ (and --) do allocate new elements: •inserter, back_inserter, front_inserter
dequeue<double> dq(10, 3.14); // 10 elements
list<double> ld; // empty by default
…
copy(dq.begin(), dq.end(), back_inserter(ld));
// new elements added at the end of ld
Version 1.1 (January 2002) C++ STL 40
AlgorithmsSort/Merge Operations on
Sequencessort() stable_sort()Sort a sequence (keeping duplicate elements
orders)partial_sort() Sort the beginning of a sequencepartial_sort_copy() Copy, sort, and detect and isolate consecutive
duplicatesunique_copy() Copy and sort the beginningnth_element() Send nth element to its placelower_bound() upper_bound() Find first (last) position of some value
compatible with the orderequal_range() Find a value intervalbinary_search() Find a value within a sorted sequencemerge() inplace_merge() Merge two (consecutive) sorted
sequencespartition() stable_partition() Set in front (respecting relative
order) elements satisfying some condition
Version 1.1 (January 2002) C++ STL 41
AlgorithmsSet Operations
includes() Check whether a sequence is a sub-sequence of another one
set_union() Build sorted unionset_intersection() Build sorted intersectionset_difference() Build sorted set of elements member of
first sequence and non-member of secondset_symmetric_difference() Build sorted symmetric
difference (complement of intersection within union)
These operations only work on sorted containers
Version 1.1 (January 2002) C++ STL 42
“Character” Strings
• The notion of a “character” varies• STL character strings are template
classes– parameterized by the characteristics of
characters, their “traits”:• representation• comparison (collating sequence)• copy operations• input-output
Version 1.1 (January 2002) C++ STL 43
Character Strings : basic_string
• Template class– One usual specialization :
•string basic_string<char>
– Usual properties :• Construction, destruction, conversion from char *
• Copies (value semantics but copy on write)• Indexing ([], at) ; no substrings• Catenation (+, append…)• Comparisons…
– All sequence properties, iterators, algorithms
Version 1.1 (January 2002) C++ STL 44
Character StringsExample: strings as sequence
• Converting a character string into an array of characters
vector<char> vc;
string s = "hello, world";
copy(s.begin(), s.end(), back_inserter(vc));
Version 1.1 (January 2002) C++ STL 45
Input-Output Streams
• Type driven extensible IO system• Present in C++ nearly from the
origin• Improvements in STL
– Interface and semantics cleaned up– Better extensibility (manipulators)– Homogeneity with sequences (iterators)
Version 1.1 (January 2002) C++ STL 46
Input-Output StreamsClassification by IO Medium
ios_base
ios
iostream
istream ostream
istringstream ostringstreamifstream ofstream
stringstream fstream
Version 1.1 (January 2002) C++ STL 47
Input-Output StreamsStream Manipulators
• Special operations
int x, y, z, t;cout << x << flush; // flush the stream buffercout << x << endl; // new line and flush
cout << hex << x; // print x in hexadecimal
cout << oct << x << hex << y << dec << z;cout << t;
// x printed in octal, y in hexadecimal,// z in decimal, t in decimal too (last// state of the stream)
Version 1.1 (January 2002) C++ STL 48
Input-Output StreamsStream Iterators
• Streams, like all containers, can have iterators
vector<string> v;copy( istream_iterator<string>(cin),
istream_iterator<string>(),back_inserter(v));
copy( v.begin(), v.end(),
ostream_iterator<string>(cout, ″---″));
– Note that the default constructor (istream_iterator()) corresponds to end of file
Version 1.1 (January 2002) C++ STL 49
Numerics
• Complex number (template classes)
• Numeric arrays : valarray– Standard operations on vectors– Sequence operations, iterators– Vector “slices”
• Algorithms – Accumulation, scalar product...
Version 1.1 (January 2002) C++ STL 50
Header files (1)
• Containers<vector> <list> <deque>
<queue> <stack> <map>
<set> <bitset>
• General utilities<utility> <functional>
<memory> <ctime>
• Iterators<iterator>
• Algorithms<algorithm> <cstdlib>
• Diagnostics<stdexcept> <cassert>
<cerrno>
• Strings<string> <cctype>
<cwtype> <cstring>
<cwstring> <cstdlib>
Version 1.1 (January 2002) C++ STL 51
Header files (2)
• Input-output<iosfwd> <iostream> <ios> <streambuf> <istream> <ostream><iomanip> <sstream><cstdlib> <fstream><cstdio> <cwchar>
• Localization<locale> <clocale>
• Run-time support
<limits> <climits> <cfloat> <new> <typeinfo> <exception><cstddef> <cstdarg><csetjmp> <cstdlib><ctime> <csignal>
• Numerics<complex> <valarray> <numerics> <cmath> <cstdlib>
Version 1.1 (January 2002) C++ STL 52
References
Bjarne StroustrupThe C++ Programming Language, 3rd EditionAddison-Wesley, 1997
Nicolai M. JosuttisThe C++ Standard Library: A Tutorial and
ReferenceAddison-Wesley, 1999
Scott MeyersEffective STLAddison-Wesley, 2001
And many others…