stl_english

advertisement
Introduction to the ISO C++
Standard Template Library (STL)
Jean-Paul Rigault
Professor, École supérieure en sciences informatiques (ESSI)
University of Nice Sophia Antipolis
Version 1.1 (January 2002)
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
2
Implementation Constraints
• Usable directly and
easily
• Efficient
• Neutral policy
• Primitive
• Complete
Version 1.1 (January 2002)
• Compatible with base
types
• Type-safe
• Support for all
programming styles
• Extensible
C++ STL
3
Organization of the C++ STL
• Namespace std
• Header files
– Recover ANSI C header files
(<cXXXX>  <XXXX.h>)
• Library elements
Containers, iterators, algorithms, general
utilities, diagnostics, strings, input-output,
localization, basic run-time support, (numerical
elements)
Version 1.1 (January 2002)
C++ STL
4
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
5
Containers : Different Types
Basic Containers
vector<T>
list<T>
dequeue<T>
vector with automatic (re)allocation
doubly linked sequence (list)
sequence with optimized indexing
Container adapters
stack<T>
LIFO
queue<T>
FIFO
priority_queue<T>
queue with priority (operator <)
Associative containers
map<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 K
multiset<K>
set with duplicate (i.e., bag) of K
Version 1.1 (January 2002)
C++ STL
6
Containers : Iterators (1)
• Model : sequence and extended pointer
rend()
begin()
rbegin()
iterator
p
--
end()
++
*p
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 << ' ';
Version 1.1 (January 2002)
C++ STL
7
Containers : Iterators (2)
• Reverse iteration
– Use a reverse iterator
list<int>::const_reverse_iterator rit;
for (rit = L.rbegin(); rit != L.rend(); rit++)
cout << *rit << ' ';
• Non const iterator
– Allow modification of container elements
list<int>::reverse_iterator rit;
for (rit = L.rbegin(); rit != L.rend(); rit++)
*rit = 10;
Version 1.1 (January 2002)
C++ STL
8
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
9
Containers: Common Characteristics
• Member-types
value_type
iterator
const_iterator
reverse_iterator
const_reverse_iterator
reference
const_reference
Version 1.1 (January 2002)
type of value
~ value_type*
~ const value_type*
~ value_type*
~ const value_type*
~ value_type&
~ const value_type&
C++ STL
10
Containers : Common Characteristics
Common Member-Functions (1)
• Iteration
begin()
end()
rbegin()
rend()
“Point” to first element
“Point” to just after last element
“Point” to first element in reverse order
“Point” to just after last element in reverse order
• Access to contents
front()
last()
[]
at()
Version 1.1 (January 2002)
Reference to first element
Reference to last element
Indexing without bound checking (N/A for lists)
Indexing with bound checking (N/A for lists)
C++ STL
11
Containers : Common Characteristics
Common Member-Functions (2)
• Operations on lists, stacks, and queues
push_back()
pop_back()
push_front()
pop_front()
Append (add after last)
Remove last element and return its value
Prepend (add before first)
Remove first element and return its value
• Operations on list (sequence)
insert()
erase()
clear()
Version 1.1 (January 2002)
Insert before an element
Remove an element
Remove all elements
C++ STL
12
Containers : Common Characteristics
Common Member-Functions (3)
• Miscellaneous operations
size()
empty()
max_size()
swap()
==
!=
<
Number of elements
Is the container empty ?
Maximum possible size
Swap two elements
Comparisons
• Assignments
assign(n)
value)
assign(n, x)
assign(first, last)
=
Version 1.1 (January 2002)
Assign n elements (to their default
Assign n copies of x
Assign all elements between iterators
first and last to default value
Ordinary (copy) assignment
C++ STL
13
Containers : Common Characteristics
Common Member-Functions (4)
• Construction and destruction
container()
container(n)
container(n, x)
container(first, last)
container(other_container)
~container()
Version 1.1 (January 2002)
C++ STL
Empty container
Container with n elements
(initialized to their default value)
Container with n copies of
element x
Container with elements copied
from interval between iterators
first et last
Copy of container
Destructor
14
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
15
Containers : Remarks (2)
• Associative containers (maps and sets)
specific member functions
operator[](k)
find(k)
lower_bound(k)
upper_bound(k)
equal_range(k)
Version 1.1 (January 2002)
Access to element with key k
Find element with key k
The smallest element with key k
The largest element with key k
Interval of elements with key k
C++ STL
16
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,
cout << it->first << ' ' << it->second;
Version 1.1 (January 2002)
C++ STL
char>
17
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
18
Containers : Operation Complexity
Indexing
[], at()
vector
list
dequeue
O(1)
O(1)
stack
queue
priority_queue
map
multimap
set
multiset
string
array
valarray
bitset
Version 1.1 (January 2002)
O(log n)+
O(log n)+
O(1)
O(1)
O(1)
O(1)
List
operations
O(n)+
O(1)
O(n)
Operations
on the head of
a sequence
O(1)
O(1)
O(n)
O(n)
O(log n)
O(1)
O(log n)
O(log
O(log
O(log
O(log
O(n)+
O(n)+
C++ STL
Operations
on the tail of
a sequence
O(1)+
O(1)
O(1)
O(1)
O(1)
n)+
n)+
n)+
n)+
O(1)+
19
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
20
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
21
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 =
Version 1.1 (January 2002)
C++ STL
find(L.begin(),
L.end(), 7);
22
Algorithms on Sequences/Sets (3)
• Sequence filtering
bool 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
23
Algorithms on Sequences/Sets (4)
• Transforming a sequence
int 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
24
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
25
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 like
bool pred(InputIterator::value_type)
Version 1.1 (January 2002)
C++ STL
26
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 object
int n =
count_if(L.begin(), L.end(), criter);
Version 1.1 (January 2002)
C++ STL
27
Algorithms on Sequences/Sets
Functionals (1)
class Figure {
public:
...
void draw() const;
void rotate(int angle);
};
list<Figure> LF;
...
for_each(LF.begin(), LF.end(), &Figure::draw);

Version 1.1 (January 2002)
C++ STL
Error !
28
Algorithms on Sequences/Sets
Functionals (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
29
Algorithms on Sequences/Sets
Functionals (3)
• Predefined function-objects
negate<type>(p)
-- p
plus<type>(p1, p2)
p1 + p2
and minus, multiplies, divides, modulus
equal_to<type>(p1, p2)
p1 == p2
and not_equal_to
less<type>(p1, p2)
p1 < p2
and greater, less_equal, greater_equal
logical_not<type>(p)
!p
logical_and<type>(p1, p2) p1 && p2
and logical_or
Version 1.1 (January 2002)
C++ STL
30
Algorithms on Sequences/Sets
Functionals (4)
• Function adapters for function-objects
it = 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
31
Algorithms on Sequences/Sets
Functionals (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 functionobject
Version 1.1 (January 2002)
C++ STL
32
Algorithms on Sequences/Sets
Functionals (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 functionVersion 1.1 (January 2002)
C++ STL
33
Algorithms on Sequences/Sets
Functionals (7)
• Composing function-object adapters
list<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
34
Algorithms
Non-Modifying Operations on
Sequences
for_each()
Apply a function to each element
find()
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
sequence
adjacent_find()
Find consecutive duplicate elements
count()
count_if() Count all occurrences of an element with a
given value (resp. satisfying some condition)
mismatch()
Find all elements differing between two
sequences
equal()
Check sequence equality
search()
Find a sub-sequence within another sequence
find_end()
Find the last occurrence of a sub-sequence within
another sequence
search_n()
Find the nth occurrence of a sub-sequence within
another sequence
Version 1.1 (January 2002)
C++ STL
35
Algorithms
Modifying Operations on Sequences
(1)
transform()
Apply a function to all elements
copy() copy_backward() Copy a sequence from the beginning or
the end
swap() iter_swap() Swap two elements pointed to by iterators
swap_ranges()
Swap elements between two sequences
replace() 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 value
generate() generate_n() Replace (first n) elements with a given
value by the result of some operation
Version 1.1 (January 2002)
C++ STL
36
Algorithms
Modifying Operations on Sequences
(2)
remove() remove_if()
Remove elements with a given value or
satisfying some condition
remove_copy() remove_copy_if() Copy a sequence, removing
elements with a given value or satisfying some
condition
unique()
Detect and isolate consecutive duplicates
unique_copy()
Copy a sequence , removing consecutive
duplicates
reverse() reverse_copy() Copy a sequence in reverse order
rotate() rotate_copy() Copy a sequence together with circular
permutation
random_shuffle()
Permute elements according to an uniform
distribution
Version 1.1 (January 2002)
C++ STL
37
Algorithms
Modifying 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 elements
list<double> ld; // empty by default
…
copy(dq.begin(), dq.end(), ld.begin());
// likely to crash!!
Version 1.1 (January 2002)
C++ STL
38
Algorithms
Modifying 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
39
Algorithms
Sort/Merge Operations on Sequences
sort() stable_sort()Sort a sequence (keeping duplicate elements
orders)
partial_sort()
Sort the beginning of a sequence
partial_sort_copy() Copy, sort, and detect and isolate consecutive
duplicates
unique_copy()
Copy and sort the beginning
nth_element()
Send nth element to its place
lower_bound() upper_bound() Find first (last) position of some
value compatible with the order
equal_range()
Find a value interval
binary_search()
Find a value within a sorted sequence
merge() inplace_merge() Merge two (consecutive) sorted
sequences
partition() stable_partition() Set in front (respecting relative
order) elements
satisfying some condition
Version 1.1 (January 2002)
C++ STL
40
Algorithms
Set Operations
includes()
Check whether a sequence is a sub-sequence
of another one
set_union()
Build sorted union
set_intersection() Build sorted intersection
set_difference()
Build sorted set of elements member of first
sequence and non-member of second
set_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
41
“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
42
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
43
Character Strings
Example: 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
44
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
45
Input-Output Streams
Classification by IO Medium
ios_base
ios
istream
ostream
iostream
ifstream istringstream
ostringstream
stringstream
Version 1.1 (January 2002)
ofstream
fstream
C++ STL
46
Input-Output Streams
Stream Manipulators
• Special operations
int x, y, z, t;
cout << x << flush;
cout << x << endl;
// flush the stream buffer
// new line and flush
cout << hex << x;
// print x in hexadecimal
cout << oct
cout << t;
//
//
//
Version 1.1 (January 2002)
<< x << hex << y << dec << z;
x printed in octal, y in hexadecimal,
z in decimal, t in decimal too (last
state of the stream)
C++ STL
47
Input-Output Streams
Stream 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
48
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
49
Header files (1)
• Containers
• Algorithms
<vector> <list> <deque>
<queue> <stack> <map>
<set> <bitset>
<algorithm> <cstdlib>
• General utilities
<stdexcept> <cassert>
<cerrno>
<utility> <functional>
<memory> <ctime>
• Iterators
<iterator>
Version 1.1 (January 2002)
• Diagnostics
• Strings
<string> <cctype>
<cwtype> <cstring>
<cwstring> <cstdlib>
C++ STL
50
Header files (2)
• Input-output
• Run-time support
<iosfwd> <iostream>
<ios> <streambuf>
<istream> <ostream>
<iomanip> <sstream>
<cstdlib> <fstream>
<cstdio> <cwchar>
<limits> <climits>
<cfloat> <new>
<typeinfo> <exception>
<cstddef> <cstdarg>
<csetjmp> <cstdlib>
<ctime> <csignal>
• Localization
• Numerics
<locale> <clocale>
<complex> <valarray>
<numerics> <cmath>
<cstdlib>
Version 1.1 (January 2002)
C++ STL
51
References
Bjarne Stroustrup
The C++ Programming Language, 3rd Edition
Addison-Wesley, 1997
Nicolai M. Josuttis
The C++ Standard Library: A Tutorial and Reference
Addison-Wesley, 1999
Scott Meyers
Effective STL
Addison-Wesley, 2001
And many others…
Version 1.1 (January 2002)
C++ STL
52
Download