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

Slides:



Advertisements
Similar presentations
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Advertisements

Multimaps. Resources -- web For each new class, browse its methods These sites are richly linked, and contain indexes, examples, documents and other resources.
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
Mutating Algorithms All the algorithms we have seen have not modified the containers Some algorithms do modify values They do not modify iterators, only.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
The Standard Template Library. Books on standard C++ library Nicolai M. Josuttis: C++ Standard Library: A tutorial and Reference, 1st, Pearson 1999, Nicolai.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
Standard Template Library C++ introduced both object-oriented ideas, as well as templates to C Templates are ways to write general code around objects.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Writing Your Own STL Container Ray Lischner
Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
STL Algorithms algorithms independent of containers.
Containers and Iterators CNS 3370 Copyright 2003, Fresh Sources, Inc.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
 2006 Pearson Education, Inc. All rights reserved Standard Template Library (STL)
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Data Structures Using C++ 2E Chapter 13 Standard Template Library (STL) II.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Intro to the C++ Std Library.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Templates code reuse - inheritance - template classes template classes - a class that is not data-type specific - eg. a class of Array of any type - intArray,
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
Lecture 7 : Intro. to STL (Standard Template Library)
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
CS 403: Programming Languages Lecture 24 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Introduction to Templates and Standard Template Library 1.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
Object-Oriented Programming (OOP) Lecture No. 41
CNS 3370 Algorithms.
Standard Template Library (STL)
Chapter 22: Standard Template Library (STL)
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
A Sorted, Unique Key Container
Generic Programming Karl Lieberherr 12/1/2018 Generic Programming.
Containers, Iterators, Algorithms, Thrust
Containers and the Standard Template Library (STL)
Class string and String Stream Processing
Standard Template Library
Standard Template Library
An Introduction to STL.
A dictionary lookup mechanism
Standard Template Library
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Containers : Operation Complexity Version 1.1 (January 2002) C++ STL

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

“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

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

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

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

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

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

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

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

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

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

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