Sei sulla pagina 1di 23

Lecture 6

Template
&
Standard Template Library

Computer Programming II

Objectives

Function Template
Class Template
Standard Template Library (STL)
STLs vector class
STLs set class
STLs map class

Computer Programming II

Introduction
Template allows us to write generic functions
or classes (called function template, class
template) that accept any data type as
parameters or attributes.
During compilation, the compiler will produce
a separate definition for every data type that
uses the template.

Computer Programming II

Function Template
Recall the function to swap integers:
void Swap (int& m, int& n) {
int temp = m;
m = n;
n = temp;
}

To sort string, we would need a


different function:
void Swap (string& s1, string& s2) {
string temp = s1;
s1 = s2;
s2 = temp;
}

Computer Programming II

These 2 functions
do the same thing,
only different in the
data type of objects
they swap.
We can avoid
writing the
redundant code by
replacing both
functions with a
function template.

Function Template
Template version of Swap() function:
template <typename T>
void Swap(T& x, T& y) {
T temp = x;
x = y;
y = temp;
}
int main() {
int m = 22, n = 66;
Swap(m, n);
// integers
cout << "m = " << m << endl
<< "n = " << n << endl;
string s1 = "Michael", s2 = "Kelly";
Swap(s1, s2); // strings
cout << "s1 = " << s1 << endl
<< "s2 = " << s2 << endl;
return 0;
}

Computer Programming II

The symbol T is
called type
parameter. It is
replaced by an
actual type when the
function is invoked.
Compiler produces 2
definitions of
Swap() functions:
one for int, one for
string
Output:
m = 66
n = 22
s1 = Kelly
s2 = Michael

Declaring Function Template


Function templates are declared in the same way as
ordinary functions, except that it is preceded by the
specification below:
template <typename T> // new, less confusing
or
template <class T>
// old, confusing, class?

and the type parameter T may be used in place of


ordinary data types within the function definition.
The word typename/class here means any type.
A template may have several type parameters:
template <typename T, typename U, typename V>

Computer Programming II

Declaring Class Template


Class templates are declared the same way as ordinary
class, except that it is preceded by the specification
below:
template <typename T>
class X { ... };
A class template may have several type parameters.
template <typename T, typename U>
class X { ... };

Computer Programming II

Class Template
Define a class template
Pair that have 2 attributes
of the same type.
template <typename T>
class Pair {
T a;
T b;
public:
void set (T a, T b) {
this->a = a;
this->b = b;
}
void print() const {
cout << "(" << a << ","
<< b << ")\n";
}
};

Computer Programming II

int main() {
Pair<int> p1;
p1.set (3,5);
p1.print();
Pair<string> p2;
p2.set ("Peter",
"Jackson");
p2.print();
Pair<char> p3;
p3.set ('P','J');
p3.print();
return 0;
}
Output:
(3,5)
(Peter,Jackson)
(P,J)

Class Template
Class template allows us to
write one class that works
for many data types
template <typename T>
class Pair {
T a;
T b;
public:
void set (T a, T b) {
this->a = a;
this->b = b;
}
void print() const {
cout << "(" << a << ","
<< b << ")\n";
}
};

Computer Programming II

int main() {
Pair<int> p1;
p1.set (3,5);
p1.print();
Pair<string> p2;
p2.set ("Peter",
"Jackson");
p2.print();
Pair<char> p3;
p3.set ('P','J');
p3.print();
return 0;
}
Output:
(3,5)
(Peter,Jackson)
(P,J)

Class Template : Multiple Type Parameters


Class template that can
have different types of
attributes
template <typename T, typename U>
class Pair {
T a;
U b;
public:
void set (T a, U b) {
this->a = a;
this->b = b;
}
void print() const {
cout << "(" << a << ","
<< b << ")\n";
}
};

Computer Programming II

int main() {
Pair<int,char> p1;
p1.set (1, 'A');
p1.print();
Pair<char,string> p2;
p2.set ('B',"Boy");
p2.print();
Pair<int,int> p3;
p3.set (99,99);
p3.print();
return 0;
}
Output:
(1,A)
(B,Boy)
(99,99)

10

Standard Template Library


The Standard Template Library (STL) is part of the
standard C++ library. STL has very powerful features.
STL has 3 basic components: Containers, Algorithms,
Iterators
Container: An STL container is a data structure or
simply a collection of objects. Example: vector,
list, set, map, etc
Algorithm: An STL algorithm is a function for
processing containers contents. Example: copy,
sort, find, etc

Computer Programming II

11

STL Container Basics


STL has 7 basic containers divided into 2 groups:
Sequential: access by index
Associative: access by key
Container
list

Type
Sequential

Description
Bidirectional linked list of elements

vector * Sequential

Array that grows and shrinks as needed

deque

Sequential

Array with efficient insertions/deletions at


either end

set *

Associative

Collection of non-duplicate keys

multiset Associative

A set with duplicates allowed

map *

Collection of non-duplicate elements with


access by key

Associative

multimap Associative

A map with duplicates allowed

* Covered in this lecture


Computer Programming II

12

STL vector Class


We can use the vector class as if it is an array that
can be resized dynamically.
Another advantage of vector is it provides random
access to its elements.
Common operations of STL's vector class:
push_back

add an item to the end of the container

pop_back

remove an item from the end of the container

operator[] return the item given a position


front
return the first item in the container
back

return the last item in the container

size

return the size of the container

clear

clear all the items in the container

Computer Programming II

13

STL vector Class

Must include this

#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
v.push_back(4);
v.push_back(2);
v.push_back(1);
v.push_back(6);
v.push_back(8);
v.push_back(3);
for (int i=0; i < v.size(); i++)
cout << v[i] << " ";
}

Computer Programming II

Must specify the type


of data to be stored.

Output:
4 2 1 6 8 3
Push the item to the
end of the vector
The items are accessed
just as if they are array
elements

14

STL vector Class


#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
int n;
do {
cout << "=> ";
cin >> n;
if (n!=-1) v.push_back(n);

With vector, we do
not need to worry
about memory
allocating for it

} while (n!=-1);

Output:
=> 1
=> 5
=> 3
=> 2
=> -1
1 5 3 2

for (int i=0; i < v.size(); i++)


cout << v[i] << " ";
return 0;

Return the total


number of
elements in vector

Computer Programming II

15

STL vector Class


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v;
v.push_back(4);
v.push_back(2);
v.push_back(7);
v.push_back(6);
cout << "Vector elements unsorted:\n";
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
sort (v.begin(), v.end());
cout << "\nVector elements sorted:\n";
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
return 0;

vector elements can


be sorted using STL
algorithm sort
function
Vector elements unsorted:
4 2 7 6
Vector elements sorted:
2 4 6 7

Computer Programming II

16

STL vector Class

A vector grows and shrinks automatically


to meet its own storage needs.

#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
nums.insert (nums.begin(), -99); // -99
nums.insert (nums.begin(), 14); // 14 -99
nums.insert (nums.end(), 57); // 14 -99 57
nums.insert (nums.begin()+1, 22);
// 14 22 -99 57
for (int i = 0; i < nums.size(); i++)
cout << nums[i] << " ";
cout << endl;
nums.erase (nums.begin()+2); // 14 22 57
nums.erase (nums.begin()); // 22 57
for (int i = 0; i < nums.size(); i++)
cout << nums[i] << endl;
return 0;
}

Computer Programming II

Insert -99 to
the beginning
of the vector
Output:
14 22 -99 57
22 57

Insert 22 to as
the 2nd element
of the vector
Erase the 3rd
element in the
vector

17

4 Basic Associative Containers: set,


multiset, map, and multimap
A set is a collection of non-duplicate sorted elements called
keys.
For example, the set below contains 3 keys:
{ "Apple", "Boy", "Cat" }
A map is a collection of (key,value) pairs sorted by the
keys; in each pair, the 1st element is a non-duplicate key, the
2nd element is the value associated with the key.
For example, the map below contains 3 pairs:
{ ('A', "Apple"), ('B', "Boy"), ('C', "Cat") }
Keys = {A, B, C}; Values = {Apple, Boy, Cat}
multiset and multimap allow duplicate keys.
The 4 containers automatically sort the elements inserted.

Computer Programming II

18

STL set Class


A set is a collection of non-duplicate sorted elements called keys.
set <key_type> s;
key_type is the data types of the key.
Use set when you want a sorted collection and you do not need
random access to its elements.
Use insert() method to insert an element into a set:
set <int> s;
s.insert (321);
Duplicates are ignored when inserted.
iterator is required to iterate/visit the elements in set. Operator[] is
not supported.
Use find() method to look up a specified key in a set .

Computer Programming II

19

STL Iterators
Iterator: An STL iterator is a mechanism (pointer) for
accessing the elements in a container one at a time.
The type of iterator must match the type of container
in order for the iterator to work.
set<int> s;
for (set<int>::iterator it = s.begin();
it != s.end();
it++)
cout << *it << " ";

Not all STL containers support the access to its


elements via operator[]. Iterator is useful in this case.
STL algorithms (find, sort) etc) use iterators to
process STL containers.
Computer Programming II

20

STL set Class


#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s;
s.insert (321);
s.insert (-999);
s.insert (18);
s.insert (-999); // duplicate is ignored
set<int>::iterator it = s.begin();
while (it != s.end())
cout << *it++ << endl; // -999 18 321
int target;
cout << "Enter an integer: ";
cin >> target;
it = s.find (target);
if (it == s.end()) // not found
cout << target << " is NOT in set.";
else
cout << target << " is IN set.";
return 0;
}

Computer Programming II

Output1:
-999
18
321
Enter an integer:
5
5 is not in set.

Use iterator to
iterate the set.
Output2:
-999
18
321
Enter an integer:
321
321 is IN set.

21

STL map Class


A map is a collection of (key,value) pairs sorted by the keys.
map <key_type, value_type> m;
key_type and value_type are the data types of the key and
the value respectively.
map is a bit similar to the array, except that in array the index is
always int starting from 0, whereas in map the key can be of
other data type.
map cannot contain duplicates (multimap can).
map <char, string> m;
m['A'] = "Apple";
m['A'] = "Angel"; // value associated to
// key "A" is "Angel"
// from here onwards

Computer Programming II

22

STL map Class


#include <iostream>
#include <map>
using namespace std;
int main() {
map <char, string> m;
m['C'] = "Cat";
// insert
m['A'] = "Apple";
m['B'] = "Boy";
cout << m['A'] << " " // retrieve
<< m['B'] << " "
<< m['C'] << endl;
map <char, string>::iterator it;
it = m.begin();
while (it != m.end()) {
cout << it->first << " "
<< it->second << endl;
it++;
}

Computer Programming II

char key;
cout << "Enter a char: ";
cin >> key;
it = m.find (key);
if (it == m.end())
cout << key
<< " is NOT in map.";
else
cout << key << " is IN map.";
return 0;
}

Output 1:
Apple Boy Cat
A Apple
B Boy
C Cat
Enter a char: Z
Z is NOT in map

Output 2:
Apple Boy Cat
A Apple
B Boy
C Cat
Enter a char: C
C is IN map

23

Potrebbero piacerti anche