Chapter 4 - The C++ Standard Template Library (STL)
Chapter 4 - The C++ Standard Template Library (STL)
Computer Programming
Chapter 4
Standard Template Library
(STL)
Outline
▪ Introduction to Generic Programming
▪ Basics of Template
What is Template?
Types of Templates
Specialized Templates
▪ Standard Library Templates(SLT)
Basic concept of SLT (What & Why?)
Classes of SLT (Standard Library functions & OO Class Library)
Components of SLT (Containers, Algorithms, Iterators)
▪ Exception Handling
Chapter 9
Int. to Generic Programming (1/7)
What is Generic Programming?
It is a style of computer programming in which algorithms are
written in terms of types to-be-specified-later that are then
instantiated when needed for specific types provided as
parameters.
In simple word, it refers to programming/developing algorithms
with the abstraction of types
Chapter 9
Int. to Generic Programming (2/7)
Real world use cases
Chapter 9
Int. to Generic Programming (3/7)
Case study : How to solve the following problems in such a way
it works with all types (int, float, char, string etc.)?
Find the largest value of two values
Read/print/find the sum of array elements
Example 1:
is that (re)usable?
int * vi;→ sum doesn’t work . . . vi: wrong value type
struct vec3 { double x[3]; ...}; vec3 *v3 = ...;
→ sum doesn’t work . . . v3: wrong access pattern
Chapter 9
Int. to Generic Programming (4/7)
Example 1: Consider the following function:
int biggest (int arg1, int arg2){
if (arg1 > arg2)
return arg1;
else
return arg2;
}
This function very nicely finds the maximum of two integers.
What if we also need a function to find the max of two values
of other types (floats, double, char, string)?
Solution:
Rewriting the code or function overloading
Using data type of larger class (e.g. double)
Chapter 9
Int. to Generic Programming (5/7)
Function overloading?
int biggest (int arg1, int arg2) float biggest (float arg1, float arg2)
{ {
if (arg1 > arg2) if (arg1 > arg2)
return arg1; return arg1;
else else
return arg2; return arg2;
} }
Chapter 9
Int. to Generic Programming (6/7)
Can we do better?
Chapter 9
Int. to Generic Programming (7/7)
Evolution of Reusability, and Generality
Evolution of data features of Evolution of algorithmic features
programming languages of programming languages
Chapter 9
Basics of Templates (1/2)
What are Templates?
It is a tool provided by the C++ language to write a common
function/class that is independent of a data type.
It is defined as a blueprint or formula for creating a generic class
or a function.
C++ template is also known as generic functions or classes.
Templates are a placeholder for a type and are not data types by
themselves.
A programmer can create a template with some or all variables
therein having unspecified data types.
To simply put, programmer can create a single function or single
class to work with different data types using templates.
Chapter 9
Basics of Templates (2/2)
C++ templates come in two flavors:
Functions templates
Class templates
The template function/class embodies the common algorithm for
all data types.
In C++ a keyword “template” and “class/type” along with angled
bracket (<>) are used for the template’s syntax (definition).
Generic parameter is defined inside the angled bracket prefixed
with the keyword class/type.
How template works
The template gets expanded at compilation time, just like macros
and allows a function or class to work on different data types
without being rewritten.
Chapter 9
Function Templates (1/6)
Function templates are a special functions that can operate
with generic types.
A template functions can be adapted to more than one type or
class without repeating the entire code for each type.
This can be achieved using template parameters.
A template parameter is a special kind of parameter that can be
used to pass a type as argument.
Syntax:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
The function template is defined just like an ordinary function
except it start/prefixed with keyword template followed by
generic data-types inside in angular brackets.
Chapter 9
Function Templates (2/6)
Description of the Syntax:
• Generic type definition
• Instead of keyword class the
The template prefix tells the compiler
typename can be used
that this is a template, so treat it
• "class" as a synonym for "kind"
differently from a normal function.
or "category"
• It can be two or more
<class T, class U, . . . >
Chapter 9
Function Templates (3/6)
Notes:
A function template cannot be split across files
Function template specification (declaration) and implementation
must be in the same file
A function template is a pattern that describes how specific
function is constructed based on given actual types.
Type parameter said to be "bound" to the actual type passed to it
and each of the type parameters must appear at least once in
parameter list of the function.
When a function template is instantiated (called) a compiler finds
type parameters in list of function template and determine
corresponding argument for each type parameter.
The compiler uses only types of the arguments in the call
Chapter 9
Function Templates (4/6)
Example 1: Comparison algorithms
Chapter 9
Function Templates (5/6)
Example 2: Swaping two elements using function templates
Chapter 9
Function Templates (5/6)
Example 2: Swapping algorithms
Chapter 9
Function Templates (6/6)
Example 3: algorithm to print array
Note:
Try it by
changing the
array type to
other data types.
Chapter 9
Class Templates (1/6)
(a) Class Template
Sometimes, you need a class implementation that is same for all
classes, only the data types used are different.
Like function templates, you can also create class templates for
generic class operations.
When a class uses the concept of Template, then the class is
known as generic class.
Class Template can also be defined similarly to the Function
Template.
Declaration syntax instance of a class
template<class Ttype> class_name<type> ob;
class class_name{
//class member data Where type is a concrete Type
//and methods that you want the class
} members to be.
Chapter 9
Class Templates (2/6)
Example 1:
#include <iostream>
using namespace std; int main() {
template<class T> Adder<int> d (4, 5);
class Adder { d.add();
public:
T num1, num2; Adder<float> c (14.5,
Adder (T x, T y) { 65.75);
num1 = x; c.add();
num2 = y;
} return 0;
void add() { }
cout << “Sum of the numbers:
“;
cout<< num1+num2<<endl;
}
}; Chapter 9
Class Templates (3/6)
Rules and features of Class Templates
1. Member functions must be defined in the same file as the class
declaration.
2. All uses of class name as a type must be parameterized.
Like a function template, the compiler generates no codes when it
encounters a class template, but generates a real class definition when
it encounter class instantiation as follow:
Example:
Box <int> myBox ();
where
Box - the template name,
int - concrete type replaces the template parameter
myBox - the object name
Chapter 9
Class Templates (4/6)
Rules and features of Class Templates
3. If the functions are defined inside the class, then they are defined
just like ordinary functions. However, Definitions of member
functions outside class declaration must be function templates
syntax: template <class T>
returntype classname<T>::function_name(arg-list)
Example:
Chapter 9
Class Templates (5/6)
Rules and features of Class Templates
4. The name of the template parameter cannot be used more than
once in the template class’s list of template parameters
template <class T, class U> //Error
class X {
//rest of the class
};
However, the same name for a template parameter can be used
in the list of template parameters of two different template
classes.
Chapter 9
Specialized Templates (2/2)
Example:
#include<iostream>
using namespace std;
template<class T>
void biggest (T arg1, T arg2){
if (arg1 > arg2) cout<<"Lager Number is "<<arg1<<endl;
else if (arg1 > arg2) cout<<"Lager Number is "<<arg2<<endl;
else cout<<“The two numbers is equal”<<endl;
}
template<>
void biggest<string> (string str1, string str2){
if (str1.compare(str2) > 0) cout<<str1<<endl;
else if (str1.compare(str2) < 0) cout<<str2<<endl;
else cout<<"The two string is equal"<<endl;
}
int main(){
int a = 5, b = 4; biggest(a, b); biggest("Addis", "Ababa"); }
Chapter 9
Multiple template parameters (1/2)
Using multiple template parameters
Classes templates and function templates can have many
template parameters
Example 1: function template with multiple template parameters
Chapter 9
Multiple template parameters (2/2)
Example 2: class template with multiple template parameters
Chapter 9
Standard Template Library (STL)
What is STL?
Collections of class template for common data structures
The standard implementation of C++ provide a set of header files
where a large number of useful class templates have been defined
These files contain definitions of the class templates, their
member functions and a number of global associated functions.
The global associated functions implement commonly used
algorithms.
STL provides powerful, template-based, reusable components that
implement many common data structures and algorithms used to
process those data structures.
The STL was conceived and designed for performance and
flexibility.
Chapter 9
STL: Components
STL provides four components called algorithms, containers,
functions, and iterators :
1. Containers
Generic "off-the-shelf" class templates for storing collections of data
2. Algorithms (function objects)
Generic "off-the-shelf" function templates for operating on containers
3. Iterators
Generalized "smart" pointers that allow algorithms to operate on
almost any container
Note:
The templates and iterators make
the algorithms independent of
containers respectively.
Chapter 9
STL: Components (cont’d)
Containers, Iterators, Algorithms
Chapter 9
STL: Components (cont’d)
The common Containers, Iterators and Algorithms:
Chapter 9
STL: Containers
STL Container Categories:
The C++ container library categorizes containers into four classes:
Chapter 9
STL: Containers (cont’d)
STL Container Categories:
Chapter 9
STL: Containers (cont’d)
Containers descriptions:
No Containers Descriptions
Bidirectional/Doubly linked list
1 list Best for rapid insertion and deletion anywhere.
"Array" that grows automatically,
2 vector Best for rapid insertion and deletion at back.
Support direct access to any element via operator "[]".
"Array" that grows automatically.
3 deque Best for rapid insertion and deletion at front and back.
Set doesn’t duplicate element.
set and Multiset is a set that allows duplicate elements
4 multiset Elements are automatically sorted.
Best for rapid lookup (searching) of element.
map and Map is collection of (key, value) pairs with non-duplicate key
Multimap is a set that allows duplicate elements
5 multimap Elements are automatically sorted by key.
Best for rapid lookup of key.
Chapter 9
STL: Iterators
Iterators are pointer-like entities that are used to access individual
elements in a container.
Chapter 9
STL: Iterators (cont’d)
Iterators and their Characteristics (cont’d)
Iterator Access method Direction of movement I/O capability
Input Linear Forward only Read-only
Output Linear Forward only Write-only
Forward Linear Forward only Read/Write
Bidirectional Linear Forward & backward Read/Write
Random Random Forward & backward Read/Write
Note:
The “=“ operator either used as an assignment operator or equal operator(=)
Every algorithm requires an iterator with a certain level of capability for example
to use the [] operator you need a random access iterator
However, not every iterator can be used with every container for example the list
class provides no random access iterator
Chapter 9
Containers and corresponding Iterators
Vector Container
Set Container
Map Container
Chapter 9
Vector Containers
Vectors is a sequence container class that implements dynamic
arrays capable of resizing itself automatically .
The resizing occurs after an element has been added or deleted
from the vector.
Vectors are not ordered in C++
Storage is handled automatically by the container.
Like array a vector stores the elements in contiguous memory
locations and allocates the memory as needed at run time
The elements can be easily accessed and traversed across using
iterators.
Declaration Syntax:
vector< object_type > vector_variable_name;
Chapter 9
Vector Containers (cont’d)
Some Iterators of Vector
Function Description
push_back() and adds a new element at the end and removes a last element from the
pop_back() vector respectively
empty() determines whether the vector is empty or not.
insert() inserts new element at the specified position.
resize() modifies the size of the vector.
clear() removes all the elements from the vector.
size() and capacity() determines a number of elements in the vector and the current capacity
of the vector respectively
end() refers to the past-last-element in the vector.
begin() points the first element of the vector.
max_size() determines the maximum size that vector can hold.
cend() and cbegin() refers to the past-last and the firs element in the vector respectively
crbegin() and It refers to the last character of the vector and element preceding the
crend() first element of the vector respectively
Chapter 9
Vector Containers (cont’d)
Example: Demonstration of vector and its iterators
#include <iostream>
#include <vector>
using namespace std;
int main(){
//vector declaration and initailization
vector<int> nums = {45, 85, 96, 23, 25};
Chapter 9
Vector Containers (cont’d)
Example ….
// checks if the vector is empty or not
if (nums.empty() == false)
cout << "\nVector is not empty";
else
cout << "\nVector is empty";
vector<int> items;
//print the size of the vector and capacity after insertion
cout<<"\n\n Second Vecor:\n";
cout<<"Size of Vector: "<<items.size()<<endl;
cout<<"Capacity of Vector: "<<items.capacity()<<endl;
//Printing the output of vector ‘a’ using iterators crbegin() and crend()
cout << "\nOutput of crbegin and crend Function: ";
for (auto ir = items.cbegin(); ir != items.cend(); ++ir)
cout << *ir << " ";
Chapter 9
Vector Containers (cont’d)
Example ….
// resizing the vector ‘a’ to size 4
items.resize(4);
return 0;
}
Chapter 9
Set Containers
Set is a C++ STL container used to store the unique elements
All the elements are stored in a sorted manner.
Once the value is stored in the set, it cannot be modified within
the set.
However, the elements can be removed and then modified value
of the element can be added.
Sets are traversed using the iterators.
Require to include the two main header files to work with the sets
Use set when you want a sorted collection and you do not need
random access to its elements.
Duplicates are ignored when elements are inserted
Chapter 9
Set Containers (cont’d)
Some Iterators of Set
Function Description
insert() Inserts a new element to the set.
begin() points the first element of the set.
end() points to the theoretical element that follows last element in the set.
empty() determines whether the set is empty or not.
erase() used to delete the elements from the set
Returns an iterator based on the position of the element if it is found,
find) else return iterator at the end
size() determines a number of elements in the set
clear() removes all the elements from the vector.
lower_bound(X) Returns an iterator to upper bound.
upper_bound(X) Returns an iterator to lower bound
cend() and cbegin() refers to the past-last and the firs element in the set respectively
crbegin() and It refers to the last character of the set and element preceding the first
crend() element of the set respectively
Chapter 9
Set Containers (cont’d)
Example: Demonstration of set and its iterators
#include <iostream>
#include <iterator>
Instead this header file can be used
#include <set>
#include <algorithm> #include< bits/stdc++.h >
int main(){
// empty set container
set<int, greater<int> > s1;
Chapter 9
Set Containers (cont’d)
Example …. // printing set s1
set<int, greater<int> >::iterator itr;
cout << "\nThe set s1 is : \n";
for (itr = s1.begin(); itr != s1.end(); itr++)
cout << *itr<<" ";
cout << endl;
// set initialization
sample1 = { 1, 2, 3, 4, 5 }; sample2 = { 6, 7, 8, 1 };
// Merge two sets using merge() algorithm and move the result to sample3
merge(sample1.begin(), sample1.end(), sample2.begin(), sample2.end(),
inserter(sample3, sample3.begin()));
// copy assignment
sample1 = sample3;
Chapter 9
Set Containers (cont’d)
Example ….
// Print the sets
for (auto it = sample1.begin(); it != sample1.end(); ++it)
cout << *it << " ";
cout << endl;
return 0;
}
Chapter 9
Map Containers
Map is an associative container that store the elements as a
combination of key-value pairs (like dictionary).
Each key is unique and it can be inserted or deleted but cannot be
altered.
However, the values associated with keys can be changed.
By default keys are in ascending order
Syntax:
map < key_datatype, value_datatype > map_name;
Here,
key_datatype = datatype of key
value_datatype = datatypes of value corresponding to key
map_name = Name of the map
Chapter 9
Map Containers (cont’d)
Some Iterators of Map
Function Description
insert() Insert elements with a particular key in the map container
clear() removes all the elements from the vector.
begin() points the first element of the map
end() points to the theoretical element that follows last element in the map.
operator[] reference the element present at position given inside the operator
size() determines a number of elements in the map
empty() determines whether the vector is empty or not.
max_size() determines the maximum size that map can hold.
find(loc) it points to the element if element found at loc.
erase (iterator loc) it removes the element which is specified at a location by the iterator
upper_bound() Return iterator to the upper bound
lower_bound() Return iterator to the lower bound
Chapter 9
Map Containers (cont’d)
Example: Demonstration of map and its iterators
#include <iostream>
#include <iterator>
#include <map>
int main(){
//initialize map
map<int, string> Employees = {{101, "Mulalem"}, {105, "John"},
{103, "Daniel"}, {104, "Kebede"},
{102, "Aman"}};
Chapter 9
Practical Exercise (2/2)
5. Write a template function called findLargestElement that accepts a
vector as a parameter and returns the largest element in that vector.
Write a driver program to test your function.
6. Write a program that uses the map template class to compute a
histogram of positive numbers entered by the user. The map’s key should
be the number that is entered, and the value should be a counter of the
number of times the key has been entered so far. Use -1 as a sentinel
value to signal the end of user input. For example, if the user inputs: 5,
12, 3, 5, 5, 3, 21, -1, then the program should output the following (not
necessarily in this order):
number occurs
3 2
5 3
12 1
21 1
Chapter 9
Summary Questions
1. Compare and discuss the advantages of function templates over
a) function overloading
b) Function macros
2. What is friend function? Explain providing an example.
3. Discuss the benefit of using STL.
4. Compare and contrast STL Iterator and smart pointers.
5. Explain the cons and pros of the following
1. Templates
2. STL containers
3. STL Iterators
6. Demonstrate Template Specialization and Variadic Templates.
7. Demonstrate how non-type template parameter is used in class
and function templates
Chapter 9
Reading Assignment
Exception Handling
Competitive Programming (very useful for programming consent)
Chapter 5
Reading Resources/Materials
Chapter 8, 17 & 18:
✔ Walter Savitch; Problem Solving With C++ [10th edition,
University of California, San Diego, 2018
Chapter 15 & 16:
✔ P. Deitel , H. Deitel; C++ how to program, 10th edition, Global
Edition (2017)
Chapter 16 & 21:
✔ Herbert Schildt; C++ from the Ground Up (3 rd Edition), 2003
Graw-Hill, California 94710 U.S.A.
Chapter 30 - 33:
✔ Bjarne Stroustrup;The C++ Programming Language [4th
Edition], Pearson Education, Inc , 2013
Chapter 9
Thank You
For Your Attention!!
Chapter 9