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 9.2 Function Genericity Overloading and Templates 9.3 Class Genericity Templates 9.4 The vector Container 9.5 Case Study: Counting Computer Logins 9.6 Multidimensional vectors (Optional) 9.7 Other Standard Containers deque, stack, queue 9.8 Bitsets and Valarrays (Optional)
Chapter Objectives
Survey how reusability and genericity 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 Look at some of the other C++ standard containers (deque, stack, and queue) (Optional) Introduce valarrays and bitsets as array-based templates
Fig. 9.1
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
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; }
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. "class" as a synonym for "kind" or "category" specifies "type/kind" of types.
14
Function Template
<typename ElementType> names ElementType as a type parameter The type will be determined
by the compiler from the type of the arguments passed when Swap() is called.
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
In and of itself, the template does nothing. 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()
17
For each type parameter, type of corresponding argument determined These two types bound together
18
const int STACK_CAPACITY = 128; typedef int StackElement; class Stack { /***** Function Members *****/ public: . . . /***** Data Members *****/ private: StackElement myArray[STACK_CAPACITY]; int myTop; };
19
How did we create a new version of a stack for a different type of element?
Problems:
Changes the header file
Any program that uses this must be recompiled
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
const int STACK_CAPACITY = 128; template <typename StackElement> __________________________________ class Stack { /***** Function Members *****/ public: . . . /***** Data Members *****/ private: StackElement myArray[STACK_CAPACITY]; int myTop; };
21
22
23
24
Apply Rule 1
Each member functions definition preceded by template <typename StackElement>
25
26
Consider the addition of a friend function operator<< Second parameter is of type Stack, must parameterized
27
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
31
STL's 10 Containers
Kind of Container Sequential: Associative: STL Containers
deque, list, vector map, multimap, multiset, set priority_queue, queue, stack bitset, valarray, string
Adapters:
Non-STL:
32
33
34
vector Operations
Information about a vector's contents
v.size() v.empty() v.capacity() v.reserve()
35
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
39
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
Cannot "operate" on itself Must "re-invent the wheel" for most actions
46
Case Study: Counting Computer Logins Problem: Login information for each user on a system recorded in a file. We wish to compile a log of information for distinct users Object involved is log of user's information Operations on this object include building the object by
Reading login info for user from file Searching log for user's login info Add information if not already in file
47
Case Study: Counting Computer Logins Linear search algorithm will be used Fig. 9.5 shows declaration of class LoginLog Fig 9.6 shows program to use class LoginLog
48
9.6 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);
49
50
51
Acts like a queue (or stack) on both ends It is an ordered collection of data items Items can only be added or removed at the ends
52
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
53
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
54
Has two new operations: d.push_front(value); Push copy of value at front of d d.pop_front(value); Remove value at the front of d
55
But: insertion and deletion are not efficient in fact, take longer than for vectors.
56
deque
With deque this copying, creating, and destroying is avoided. It must copy the objects from the old vector to the Once an object is constructed, it can stay in the new vector same memory locations as It must destroy each object long as it exists in the old vector If insertions and deletions A lot of overhead!
take place at the ends of the deque.
57
58
When a data block gets full, a new one is allocated and its address is added to map.
59
The current values are copied into the middle of it. Inserts and deletes may involve crossblock element-shifting!
60
61
stack <T,
62
63
9.8 Bitsets
The C++ standard includes bitset as a container,
but it is not in STL.
Unlike arrays, bitset provides operations for manipulating the bits stored in it. They provide an excellent data structure to use to implement sets.
64
Bitsets
Operations provided Bitwise and &, bitwise or |, bitwise xor ^
Assignment operators Relational operators Subscript operator
65
ValArrays
The standard C++ library also provides the valarray class template,
Designed to carry out (mathematical) vector operations very efficiently. Highly optimized for numeric computations.
Operators provided
subscript assignment unary +, -, ~, ! size resize(n,val)
66
ValArrays
Auxiliary types that specify subsets of a valarray
slice_array gslice_array mask_array indirect_array
67