Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to the ISO C++ Standard Template Library (STL)

Similar presentations


Presentation on theme: "Introduction to the ISO C++ Standard Template Library (STL)"— Presentation transcript:

1 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)

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 elements Containers, 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 Containers vector<T> vector with automatic (re)allocation list<T> doubly linked sequence (list) dequeue<T> 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

7 Containers : Iterators (1)
Model : sequence and extended pointer rend() begin() iterator p rbegin() 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

8 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

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-types value_type type of value iterator ~ 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 element end() “Point” to just after last element rbegin() “Point” to first element in reverse order rend() “Point” to just after last element in reverse order Access to contents front() Reference to first element last() 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 queues push_back() Append (add after last) pop_back() Remove last element and return its value push_front() Prepend (add before first) pop_front() Remove first element and return its value Operations on list (sequence) insert() Insert before an element erase() Remove an element clear() Remove all elements Version 1.1 (January 2002) C++ STL

13 Containers : Common Characteristics Common Member-Functions (3)
Miscellaneous operations size() Number of elements empty() Is the container empty ? max_size() Maximum possible size swap() Swap two elements == != < Comparisons Assignments assign(n) Assign n elements (to their default value) assign(n, x) Assign n copies of x assign(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 container container(n) Container with n elements (initialized to their default value) container(n, x) Container with n copies of element x container(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 functions operator[](k) Access to element with key k find(k) Find element with key k lower_bound(k) The smallest element with key k upper_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
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>  11/02/2003 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 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

24 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

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 like bool 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 object int n = count_if(L.begin(), L.end(), criter); Version 1.1 (January 2002) C++ STL

28 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);  Error ! Version 1.1 (January 2002) C++ STL

29 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

30 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

31 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

32 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 function-object Version 1.1 (January 2002) C++ STL

33 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 function-objects (see the STL documentation) Version 1.1 (January 2002) C++ STL

34 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

35 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

36 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

37 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

38 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

39 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

40 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

41 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

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

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 Streams Classification by IO Medium
ios_base ios istream ostream iostream ifstream istringstream ostringstream ofstream stringstream fstream Version 1.1 (January 2002) C++ STL

47 Input-Output Streams Stream Manipulators
Special operations int x, y, z, t; cout << x << flush; // flush the stream buffer cout << 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 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

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) Algorithms Diagnostics Strings 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 Localization Run-time support Numerics
<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 And many others… 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


Download ppt "Introduction to the ISO C++ Standard Template Library (STL)"

Similar presentations


Ads by Google