Generic Programming and the C++ Standard Template Library
Templates provide method for creating concrete object from a parameterized instantiation.
The C++ Standard Template Library (STL) is a collection of algorithms with well defined usage interfaces that can be exploited over a range of container types.
As with C and C++, the overriding consideration in the design and implementation of the STL was efficiency.
There are 3 essential concepts in the STL: • Iterators • Containers • Algorithms
C++ Standard Template Library (STL) 1 of 21 Lecture 12 EECS 498 Winter 2000
Basic Templates
Templated Classes
template
private: Type *m_data; }
Array
C++ Standard Template Library (STL) 2 of 21 Lecture 12 EECS 498 Winter 2000 Basic Templates
Must be careful to match signatures...
template
int Foo
If function is not “inline”, then each possible version of the instantiation must have concrete version in source file.
C++ Standard Template Library (STL) 3 of 21 Lecture 12 EECS 498 Winter 2000
Iterators
• Interface between algorithm and data structure (container) • Generalization of C pointers.
Consider simple search function:
char* strchr( char* s, int c ) { while (*s != ‘\0’) if (*s == c) return s else ++s; return (char *) 0; } • How to specify sequence to be manipulated? • How to indicate current position in sequence? • How to get next element? • How to indicate end-of-sequence? • How to indicate failure?
C++ Standard Template Library (STL) 4 of 21 Lecture 12 EECS 498 Winter 2000 Iterators (cont)
Central feature of STL is generic algorithms on ranges.
A range specifies the sequence to be operated upon. All ranges have the form: [first, last) Note that this is an open interval. The last element in NOT in the sequence to be operated upon1.
Iterator defines access strategy for elements over the range.
1.All C arrays support a pointer to the element after the last element in the array. This is commonly used for testing; this model was carried forward into the STL.
C++ Standard Template Library (STL) 5 of 21 Lecture 12 EECS 498 Winter 2000
Iterator Types (Hierarchy)
• Input Can read one item at a time Can advance only • Output Can write one item at a time Can advance only • Forward Supports both read/write of elements Can advance only • Bi-directional As with forward, but can decrement • Random Access Support arbitrary “pointer” arithmetic
C++ Standard Template Library (STL) 6 of 21 Lecture 12 EECS 498 Winter 2000 Operations Supported on Iterators
• ++i, i++, --i, i-- • *i, i[n] read and/or write reference to element • i == j, i != j test if two iterators reference same element • i + n, i - n move iterator by n positions (forward/back) • i = j assign iterators i += n advance by “n” elements i -= n move back “n” elements
input output
forward
bi-directional
random access
C++ Standard Template Library (STL) 7 of 21 Lecture 12 EECS 498 Winter 2000
Iterator (examples)
typedef vector
v.push_back( “first element” ); v.push_back( “second element” ); for (i = v.begin(); i != v.end(); i++) cout << *i << endl;
C++ Standard Template Library (STL) 8 of 21 Lecture 12 EECS 498 Winter 2000 Iterator Modifiers:
• const: permit read-only behavior • reverse iterate in reverse direction (if support in collection).
note: use iter++ to advance backwards.
Every collection defines functions for obtaining iterators at extremities: • begin • end • rbegin • rend
C++ Standard Template Library (STL) 9 of 21 Lecture 12 EECS 498 Winter 2000
Function Objects
Parameterize algorithm behavior by abstracting some part of its behavior as a function. • predicates, comparitors & general functions Complete the concrete implementation of the (generic) algorithm by supplying a function with overloaded operator(). • generator: f() • unary: f(x) • binary: f(x,y)
template
C++ Standard Template Library (STL) 10 of 21 Lecture 12 EECS 498 Winter 2000 Containers
Sequential (linear or indexed lookup) • Vector: linear, contiguous storage, fast insert at end. • Deque: linear, non-contiguous storage, fast insert at front/ back • List: doubly linked, fast inserts anywhere Associative (all have keyed lookup) • Set: “set” with fast associative lookup. • Multi-Set: like Set, but permits duplicates • Map: collection of 1-1 mappings • Multi-Map: collection of 1-many mappings Adapters • Stack: LIFO • Queue: FIFO • Priority Queue: Maintains sorted order.
C++ Standard Template Library (STL) 11 of 21 Lecture 12 EECS 498 Winter 2000
Containers (cont)
Classes stored in STL containers must (minmally) have: • copy operator • operator= If the container is sorted (or associative), must define: • operator== • operator<
C++ Standard Template Library (STL) 12 of 21 Lecture 12 EECS 498 Winter 2000 Base Container operations
• Constructor: both default and Container( const Container
C++ Standard Template Library (STL) 13 of 21 Lecture 12 EECS 498 Winter 2000
Container Insertions
Must be careful that the container element was defined. There is an important distinction between insertion and overwrite. vector< int > v; ... v[n] = 17; This will crash if cell ‘n’ has been allocated.
How about multiple initialization? int a[5] = {1,2,3,4,5};
copy( a, a+5, v.begin()); // might crash copy( a, a+5, back_inserter(v) );
C++ Standard Template Library (STL) 14 of 21 Lecture 12 EECS 498 Winter 2000 Container Hierarchy
container
forward container
Associative Sequence Container
simple pair Front Back Insertion Insertion unique multiple
sorted hashed
reversible container
hashed are not part of the base random access container STL.
C++ Standard Template Library (STL) 15 of 21 Lecture 12 EECS 498 Winter 2000
Algorithms
Non-mutating
Linear Comparing Matching Counting Min/Max Search Ranges
find search count equal min
find_if find_end count_if mismatch max
adjace lexicographi min_ele search_n nt_find c_compare ment
Find_fir max_ele st_of ment
C++ Standard Template Library (STL) 16 of 21 Lecture 12 EECS 498 Winter 2000 Mutating
Copy copy copy Range backward
iter swap Swap swap swap range
replace replace replace Replace replace if copy copy if
Filling fill fill n generate generate n Range
Removing remove remove remove unique remove unique Elements if copy copy if copy
next prev rotate Permuting reverse reverse rotate per- per- copy copy muta- muta- tion tion
stable Partition partition partition
C++ Standard Template Library (STL) 17 of 21 Lecture 12 EECS 498 Winter 2000
random Random random random sample Shuffing shuffle sample n
accu- inner partial adjacent Numeric mulate product sum difference
C++ Standard Template Library (STL) 18 of 21 Lecture 12 EECS 498 Winter 2000 Sorting, Set operations
Sort Binary Set Merg Ranges search Operations
binary sort merge includes search
lower inplace set stable sort bound merge union
upper set partial sort bound intersection
partial sort equal set copy range difference
set nth element symmetric difference
is sorted
C++ Standard Template Library (STL) 19 of 21 Lecture 12 EECS 498 Winter 2000
Errata
Sometimes compiler gets confused about names. Consider:
template< class Parm, class U > Parm minus( Parm *array, U value ) { Parm::name *p; // pointer declaration or mult?
Compiler can’t tell during template building if name refers to a type, since it can’t see the definition of Parm. You can give a hint to the compiler with:
template< class Parm, class U > Parm minus( Parm *array, U value ) { typename Parm::name *p; // definite pointer declaration
C++ Standard Template Library (STL) 20 of 21 Lecture 12 EECS 498 Winter 2000 References
• The STL Primer Glass & Schuchert PTR/Prentice Hall 1996 • STL Tutorial and Reference Guide Musser & Saini Addison Wesley 1996 • Generic Programming and the STL Austern Addison Wesley 1999 • C++ Primer (3rd Edition) Lippman & Lajoie Addison Wesley 1998
C++ Standard Template Library (STL) 21 of 21 Lecture 12 EECS 498 Winter 2000