CSC-335 ADT's & Data Structures - ADT Implementations: Templates and Standard Containers)
CSC-335 ADT's & Data Structures - ADT Implementations: Templates and Standard Containers)
Chapter Contents
9.1 Introduction: The Evolution of Reusability and Genericity
Chapter Objectives
Survey how reusability themes have evolved in programming languages Study function templates Study class templates Look at vector in detail as an example of a container class template (Optional) Study multidimensional vectors
Niklaus Wirth (inventor of Pascal) Stressed data and algorithms cannot be separated
5
Function Templates
Note how similar each of the swap functions would be
The three places where the type is specified
Template Mechanism
Declare a type parameter
also called a type placeholder
void Swap(______ & first, ______ & second) { ________ temp = first; first = second; second = temp; }
Template Mechanism
The word template is a C++ keyword Specifies that what follows is
a pattern for a function not a function definition.
Type parameters (and arguments for class templates) appear within template angle brackets (< > ).
10
Template Mechanism
A function template cannot be split across files
specification and implementation must be in the same file
11
Template Mechanism
Each of the type parameters must appear at least once in parameter list of the function
compiler uses only types of the arguments in the call thus determines what types to bind to the type parameters
12
Function Template
template <typename ElementType> void Swap (ElementType &first, ElementType &second) { ElementType hold = first; first = second; second = hold; } template <class myType> void Swap (myType &first, myType &second) { ElementType hold = first; first = second; second = hold; } Int x = 10; string x = Hello;
13
Function Template
template <typename ElementType> void Swap (ElementType &first, ElementType &second) Originally, the keyword class was used instead of typename in a type-parameter list.
14
Function Template
<typename ElementType> names ElementType as a type parameter
15
or
template <class TypeParam> FunctionDefinition
where:
TypeParam is a type-parameter (placeholder)
naming the "generic" type of value(s) on which the function operates FunctionDefinition is the definition of the function, using type TypeParam.
16
Template Instantiation
The template itself does nothing specific. When the compiler encounters a template
it stores the template but doesn't generate any machine instructions.
Later, when it encounters a call to Swap() Example: Swap(int1, int2); it generates an integer instance of Swap() as shown in the next slide
17
Template Instantiation
template <class theType> void Swap (theType& first, theType& second) { theType hold = first; first = second; second = hold; } void Swap (int& first, int& second) { int hold = first; first = second; second = hold; }
18
template <class T> void printArray (const T& A[], int size) { for (int i = 0; i< size, i++) cout << A[i] << ; cout << endl; }
19
int myArray[STACK_CAPACITY];
int myTop;
};
20
Type-Independent Container
Use a class template:
the class is parameterized it receives the type of data stored in the class via a parameter (like function templates).
Recall
template <class StackElement, int theMaxSize> __________________________________ class Stack { /***** Function Members *****/ public: . . . StackElement is /***** Data Members *****/ a blank type (a private: type placeholder) StackElement myArray[theMaxSize]; to be filled in later. int myTop; };
21
class SomeClass { // ... members of SomeClass ... }; More than one type parameter may be specified: template <class TypeParam_1,..,class TypeParam_N> class SomeClass { // ... members of SomeClass ... };
22
Passes Type as an argument to the class template definition. Examples: Stack<int, 100> intSt; Stack<string, 50> stringSt; Compiler will generate two distinct definitions of Stack
two instances one for ints and one for strings.
23
3. Member functions must be defined in the same file as the class declaration.
24
Apply Rule 1
Each member functions definition preceded by template <class StackElement>
25
26
Consider the addition of a friend function operator<< Second parameter is of type Stack, must parameterized
27
template<class StackElement> ostream& operator<<(ostream& out, const Stack<StackElement>& st) { ...... ...... ...... }
28
Note that templates may have more than one type parameter
May also have ordinary value parameters
29
Components: 1. Containers:
Generic "off-the-shelf" class templates for storing collections of data
2.
Algorithms:
Generic "off-the-shelf" function templates for operating on containers
3.
Iterators:
Generalized "smart" pointers that allow algorithms to operate on almost any container
30
iterator algorithm
31
STL's 10 Containers
Kind of Container Sequential: Associative: Adapters: Non-STL: STL Containers
deque, list, vector
map, multimap, multiset, set priority_queue, queue, stack bitset, valarray, string
32
self contained
. . .
} ;
33
34
vector Operations
Information about a vector's contents
v.size() v.empty() v.capacity() v.reserve()
vector Operations
Assignment v1 = v2
Swapping v1.swap(v2)
Relational operators == implies element by element equality less than < behaves like string comparison
36
37
38
Iterators
Note from table that a subscript operator is provided
BUT this is not a generic way to access container elements
Iterators
Given a vector which has had values placed in the first 4 locations:
vector<int> v 9
v.begin()
15
3
v.end()
v.begin() will return the iterator value for the first slot, v.end() for the next empty slot
41
Iterators
Each STL container declares an iterator type can be used to define iterator objects To declare an iterator object the identifier iterator must be preceded by
name of container scope operator ::
Example:
42
Iterators
Basic operators that can be applied to iterators:
increment operator ++ decrement operator -dereferencing operator * Assignment = Addition, subtraction +, -, +=, -= vecIter + n returns iterator positioned n elements away
43
Iterators
Contrast use of subscript vs. use of iterator
ostream & operator<<(ostream & out, const vector<double> & v) { for (int i = 0; i < v.size(); i++) out << v[i] << " "; return out; }
for (vector<double>::iterator it = v.begin(); it != v.end(); it++) out << *it << " ";
44
Iterator Functions
Note Table 9-5, pg 490 Note the capability of the last two groupings
Possible to insert, erase elements of a vector anywhere in the vector Must use iterators to do this Note also these operations are as inefficient as for arrays due to the shifting required
45
Arrays Fixed size, cannot be changed during execution Cannot "operate" on itself Must "re-invent the wheel" for most actions Cannot be returned from the function Always is passed as reference to the function
Multidimensional vectors (Optional) Consider a vector whose elements are themselves vectors A vector of vectors Example
vector < vector<double> > table (ROWS, vector <double> (COLUMNS, 0, 0);
47
48
49
50
deques
Basic operations
Construct a deque (usually empty): Check if the deque is empty Push_front:
Add an element at the front of the deque
Push_back:
Add an element at the back of the deque
51
deques
Basic operations (ctd.) Front:
Retrieve the element at the front of the deque
Back:
Retrieve the element at the back of the deque
Pop_front:
Remove the element at the front of the deque
Pop_back:
Remove the element at the back of the deque View Fig. 9.7, Demonstration of STL's deque
52
53
deque
With deque this copying, creating, and destroying is avoided. Once an object is constructed, it can stay in the same memory locations It must destroy each object as long as it exists in the old vector If insertions and deletions
A lot of overhead!
54