Lecture 8
• Template classes • Introduction to the Standard Template Library (STL) –Containers • vector • map –Iterators – Algorithms
Lec 5 Programming in C++ 1
Class Templates • Class templates •Specify entire range of related classes •Generic programming – Class-template specializations •Example: Stack See tstack1.h •LIFO (last-in-first-out) structure •Describe notion of stack generically •Instantiate type-specific version template< class T > Class Stack { … } //end class stack Lec 5 Programming in C++ 2
1 Class Templates • Member functions (methods) template< class T > bool Stack< T >::push(const T &value) {…} Binds function definition to the class template
• To create a stack of doubles Stack< double > doubleStack(5); doubleStack.push(5.6); See Fig11_03.cpp
Lec 5 Programming in C++ 3
Class Templates and Nontype Parameters template< class T = String, int elements > class Stack { private: int size; Default type int top; T stackHolder[elements]; public: … } //end class stack
Stack< double, 100 > myStack;
Think: What is a advantage of this solution?
Lec 5 Programming in C++ 4
2 Standard Template Library
• Powerful, template-based components • Containers: template data structures – Objects that contain other objects • Iterators: like “pointers”, cycle through the contents of a container • Algorithms: manipulate containers, searching, sorting, etc. •Code reuse – Templates are used •Performance • STL specification requires that containers and algorithms be implemented in a way that ensures optimal run time performance.
Lec 5 Programming in C++ 5
Containers • Several types of containers – Sequence containers •Linear data structures –Dynamic array – Associative containers •Store key/value pairs •Retrieve a value given its key – Container adapters • Transform the functionality of a container • A container automatically grows when elements are added and shrinks when elements are removed.
Lec 5 Programming in C++ 6
3 Containers • Sequence containers – vector A dynamic array – deque A double-ended queue – list A linear list • Associative containers – set no duplicates – multiset duplicates allowed – map Associates one value for each key – multimap Associates multiple values for each key •Container adapters – stack – queue template
vector Sequence Container • vector // vector class-template definition #include
4 vector Sequence Container • Declarations vector
Lec 5 Programming in C++ 9
Vector Example
main(){ vector
Lec 5 Programming in C++ 10
5 Iterators • Iterators similar to pointers – Iterator operators same for all containers • * dereferences • ++ points to next element – Create an iterator given a container c • c.begin() returns iterator to first element • c.end() returns iterator to after last element – Container adapters do not support iterators Lec 5 Programming in C++ 11
Iterator Categories
• Input – Retrieve, but not store values. Forward moving only. • Output – Store, but not retrieve. Forward moving only. • Forward – Store and retrieve values. Forward moving only. • Bidirectional – Store and retrieve values. Forward and backward moving. • Random access – Store and retrieve values. Elements can be accessed randomly.
Lec 5 Programming in C++ 12
6 Iterator Operations • All – ++p, p++ • Input, bidirectional, and random iterators – *p – p = p1 – p == p1, p != p1 • Output iterators – *p = … – p = p1 • Input iterators – x = *p – p = p1 – p-> – p == p1, p != p1
Lec 5 Programming in C++ 13
Iterator Operations • Bidirectional – --p, p-- • Random access – p + i, p += i – p - i, p -= i – p[i] – p < p1, p <= p1 – p > p1, p >= p1
Lec 5 Programming in C++ 14
7 Iterators Example main(){ vector
Lec 5 Programming in C++ 15
Const and reverse Iterators
• Iterators std::vector
std::vector
Lec 5 Programming in C++ 16
8 vector Sequence Container • vector functions – v.push_back(value) • Add element to end (found in all sequence containers). – v.size() • Current number of elements stored in the vector – v.capacity() • How much vector can hold before reallocating memory – vector
Lec 5 Programming in C++ 17
vector Sequence Container • vector functions – v.insert(iterator, value ) •Inserts value before location of iterator – v.insert(iterator, array , array + SIZE) • Inserts array elements (up to, but not including array + SIZE) into vector before iterator – v.erase( iterator ) • Remove element pointed by iterator from container – v.erase( iter1, iter2 ) • Remove elements starting from iter1 and up to (not including) iter2 – v.clear() • Erases entire container
Lec 5 Programming in C++ 18
9 vector Sequence Container
• vector functions – v.front(), v.back() • Return a reference to the first and last element – v[index] = value; • Assign value to an element – v.at(index) = value; •As above, with range checking • out_of_bounds exception See Fig21_14.cpp
Lec 5 Programming in C++ 19
Common STL typedefs • typedefs for first-class containers – const_reference – reference
– pointer vector
Lec 5 Programming in C++ 20
10 Algorithms • STL has algorithms used generically across containers – Operate on elements indirectly via iterators • #include
Algorithms Example bool even(int n) { return (n % 2? false: true); } int main(){ int array[6] = { 1, 2, 3, 4, 5, 6 }; vector
11 Types of Algorithms •Copying • Searching unsorted sequences • Replacing and removing elements • Reordering a sequence •Sorting • Sorted Sequence Searching • Merging sorted sequences • Set operations • Heap operations • Minimum and maximum •Permutations • Miscellaneous
Lec 5 Programming in C++ 23
Stream Iterators
• Possible to view I/O streams as another type of container • #include
Lec 5 Programming in C++ 24
12 istream_iterator
std::istream_iterator
Lec 5 Programming in C++ 25
istream_iterator and Algorithms int main() { vector
cout << "Enter 5 integers." << endl; istream_iterator
for(int i = 0; i < v.size(); i++) cout << v[i] << " "; } End-of-stream: – istream_iterator
Lec 5 Programming in C++ 26
13 ostream_iterator
std::ostream_iterator
Lec 5 Programming in C++ 27
ostream_iterator and Algorithms std::vector
Lec 5 Programming in C++ 28
14 Usage of ostream_iterator • ostream_iterator – std::ostream_iterator< type > Name( outputStream, separator ); • type: outputs values of a certain type • outputStream: iterator output location • separator: character separating outputs •Example std::ostream_iterator
Lec 5 Programming in C++ 29
Numeric Algorithms
#include
cout << "Enter 5 integers." << endl; istream_iterator
// print sum between adjacent elements adjacent_difference(v.begin(), v.end(), ostream_iterator
Lec 5 Programming in C++ 30
15 map container • Associative container in which keys are mapped with values – A stored valued can be retrieved by its key • Key: person name • Value: telephone number – multimap container allows non unique keys • Key: City name • Value: list of clients who live in the city
Lec 5 Programming in C++ 31
map Example Student name Grade
typedef std::map
grade_list.insert(myList::value_type("David”, ‘B’)); grade_list.insert(make_pair("David”, ‘B’));
Lec 5 Programming in C++ 32
16