CMPT135 Week7 LectureNotes Yonas

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

The C++ Standard Template Library

(STL)
• C++ Templates
• Containers Library
array, vector, list, queue, stack,…
• Iterators Library
• Algorithms Library
searching, sorting, reversing,…

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 1
Weldeselassie (Ph.D.)
The C++ Standard Template Library
(STL)
• The C++ standard template library (STL) is a collection of tools that
are commonly used in software development such as containers
(variables that can store several objects), algorithms (functions that
do typical tasks such as sorting, searching, etc) and iterators
(variables that enable us to process elements of containers)
• They are C++ classes and functions that are already implemented
and are readily available for us
• Moreover they are packaged inside the std namespace
• Hence we need to include the class name of the container and also
use the std namespace whenever we need to use any of the tools in
the STL library
• Importantly these libraries are templated libraries; that is they can
work with any valid data type such as primitive data types (int,
float, char, double, bool, …) or programmer defined data types
(structs and classes)
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 2
Weldeselassie (Ph.D.)
C++ Vector
• An implementation of an array that can
 Store any data type, and
 Whose size can expand (appending more elements to the container) and shrink (removing
elements from the container)
• It comes with many member functions designed to work with vector objects such as
 Default constructor: construct a vector with 0 elements in it
 Non-default constructor: construct with a specified size (all elements initialized some default
values
 Non-default constructor: construct with specified size and an appropriate single value of element
type (all elements will be initialized to the same value)
 Copy constructor: construct a deep copy of another vector object of the same data type
 Assignment operator: assign a deep copy of a vector object of the same data type
 Destructor: that deletes the elements of the vector and sets the size to zero
 size: member function that returns the number of elements in the vector
 operator [ ]: the indexing operator
 push_back: appends the value to the vector as a last element and increment size by 1
 pop_back: delete the last element in the vector and reduce size by 1
 front: returns the first element of the vector
 back: returns the last element in the vector
 empty: test if the vector is empty (that is if size is zero). Returns true if the vector is empty.
 erase: remove one or more values from the vector
 Insert: insert one or more values into the vector
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 3
Weldeselassie (Ph.D.)
C++ vectors construction

Remark:- The vector class does


not have the output streaming
operator friend function. As
such the following statement
is syntactically wrong.
cout << A2 << endl;

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 4
Weldeselassie (Ph.D.)
Appending elements to a vector
• The most common operation with vectors is
appending element to a vector
• Appending of a new element to a vector is
performed using the push_back member
function
• This function takes a value of the same type as
the elements of the vector and appends the value
to the vector (inserts the value at the end of the
vector
• See the following example…
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 5
Weldeselassie (Ph.D.)
Appending elements to a vector

Output: 1 3 5 7 9

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 6
Weldeselassie (Ph.D.)
Pointers to vectors
• We can also declare a pointer to a vector
object as we do with simple data types
• Moreover we can use pointers to create
vectors on the heap
• We use a de-referenced pointer together with
a dot operator in order to access member
functions of vectors
• Alternatively, we can use the -> operator
which won't require de-referencing
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 7
Weldeselassie (Ph.D.)
Pointers to vectors

The same as saying This is a runtime error. Explain.


cout << a->operator[](i) << endl;
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 8
Weldeselassie (Ph.D.)
References to vectors
• Similarly, we may declare a reference variable
to a vector
• Since a reference variable is essentially
referring to the same object as the referenced
variable, any modification made to either the
variables modifies the other
• See the following example…

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 9
Weldeselassie (Ph.D.)
References to vectors

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 10
Weldeselassie (Ph.D.)
Passing vectors to functions
• We can also pass vectors as arguments to functions
• The parameter passing can be by value, by pointer or
by reference
• When using parameter passing by value, the parameter
of the function gets a copy of the argument and
therefore any modification made to the function
parameter does not modify the argument
• When using parameter passing by reference or by
pointer (together with de-referencing), then any
modification made to the function parameter will also
modify the function argument
• See the following example…
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 11
Weldeselassie (Ph.D.)
Passing vectors to functions

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 12
Weldeselassie (Ph.D.)
Returning vectors from functions
• We can also return a vector from a function
• We can return the value of a vector, a reference to a vector, or a pointer to
a vector
• Returning a vector by value will return a copy of the vector object to be
returned
• On the other hand returning by reference or by pointer, returns the vector
to be returned without making a copy
• Thus we should not return a local vector object by pointer or reference
because the vector object will be destructed when we go out of the
function
• We can also use the copy constructor or the assignment operator in order
to copy the returned vector to a vector of the same data type
• Remember the copy constructor and the assignment operator are both
overloaded in the vector class and as such a deep copy of the right hand
side operand is copied or assigned to the left hand side operand
• See the following example…
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 13
Weldeselassie (Ph.D.)
Returning vectors from functions

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 14
Weldeselassie (Ph.D.)
Deleting the last element of a vector
• In order to delete the last element of a vector, use the
pop_back() member function
• In order to test this member function, perform the
following steps:
 Create a vector and push_back two or more values
 Print the first element using front() member function
 Print the last element using back() member function
 Delete the last element using pop_back() member
function
 Print the first element using front() member function [You
must get the same front element as before]
 Print the last element using back() member function [You
must get a different last element]
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 15
Weldeselassie (Ph.D.)
Deleting the last element of a vector

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 16
Weldeselassie (Ph.D.)
Iterators
• In C++, an iterator is a position specifier in a vector or other containers
• They are implemented as pointers
• There are two types of iterators: forward itarators and reverse iterators
• When a forward iterator is incremented, it moves forward
• When a reverse iterator is incremented, it moves backwards
• There are four pre-defined iterator values for any container:
 begin(): forward iterator value specifiying the beginning of a container
✓ end(): forward iterator value specifiying the end of a container
✓ rbegin(): reverse iterator value specifiying the beginning of a container in a
reverse order
✓ rend(): reverse iterator value specifiying the end of a container in a reverse
order
• Just like with pointers, we can perform arithmetic operations with
iterators to locate any element of a container
• It should be noted that forward and reverse iterators are different data
types and therefore can not be used interchangeably
• See the following example…
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 17
Weldeselassie (Ph.D.)
Iterators

forward iterator

reverse iterator

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 18
Weldeselassie (Ph.D.)
Iterators

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 19
Weldeselassie (Ph.D.)
Constant Iterators
• If a container (such as a vector) is a constant, then neither a
forward nor a reverse iterator can be used with such a
container
• Why? Because iterators are designed to access elements of
containers for read and write purposes but a constant
container can not be modified
• For this reason, C++ provides constant iterators that can be
used with constant containers
• These constant iterators are called const_iterator and
const_reverse_iterator
• The const_iterator traverses the elements of a container in
the forward order while the const_reverse_iterator
traverses the elements of a container in a reverse order
• See the example below
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 20
Weldeselassie (Ph.D.)
Constant Iterators

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 21
Weldeselassie (Ph.D.)
Iterator out of bound errors
• Extra care is required when we use iterators as it is
common to get into runtime errors whenever we use
iterators
• We can run into two types of runtime errors when using
iterators as described below
 If a forward iterator is assigned an iterator value less than
begin() or greater than end()
 If a reverse iterator is assigned an iterator value less than
rbegin() or greater than rend()
 If we try to dereference a forward iterator value that is less than
begin() or greater than or equal to end()
 If we try to dereference a reverse iterator value that is less than
rbegin() or greater than or equal to rend()
• Analyze the following program and determine its output
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 22
Weldeselassie (Ph.D.)
Iterator out of bound errors

Runtime Error

Runtime Error
When at last it gets assigned a.begin()-1

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 23
Weldeselassie (Ph.D.)
Using Iterators
• We can use iterators to delete an element or several elements from a vector
 erase(it): deletes an element at the position specified by it argument and
then returns a new (updated) iterator value pointing to the same position
where it was pointing to
 erase(it1, it2): deletes all the elements starting from it1 (inclusive) up
to it2 (exclusive) and then returns a new (updated) iterator value pointing to
the same position where it2 was pointing to
• We can also use iterators to insert an element or several elements at specified
iterator positions as follows
 insert(it, value): inserts the value argument at the position specified
by it and then returns a new (updated) iterator value pointing to the same
position where it was pointing to
 insert(it, num, value): inserts num copies of the value argument at
the position specified by it and then returns a new (updated) iterator value
pointing to the first element inserted (it will return the end() iterator value if
num is 0)
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 24
Weldeselassie (Ph.D.)
Using Iterators

0 4 8 12 16 20 24 28 32 36

0 4 12 16 20 24 28 32 36

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 25
Weldeselassie (Ph.D.)
Using Iterators
0 4 12 16 32 36

21 0 4 12 16 32 36

21 0 4 12 16 32 36 29

21 0 4 33 12 16 32 36 29

21 0 4 33 12 37 37 37 16 32 36 29

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 26
Weldeselassie (Ph.D.)
Using Iterators
• It should be noted that every time we insert, erase,
push_back or pop_back an element or several elements
from a vector, then
 All iterator values of the vector such as begin(), end(),
rbegin(), and rend() will be invalidated
• This means if an iterator variable was declared and
assigned some iterator value (such as begin(), end(),
rbegin(), rend(), or any other iterator value such as begin()
+ 2); then
 Such an iterator variable should never be used after
the iterator values of the vector are invalidated
because of erase, insert, push_back, or pop_back
operations
• See the following example
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 27
Weldeselassie (Ph.D.)
Using Iterators

Runtime error. Why?


Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 28
Weldeselassie (Ph.D.)
C++ STL algorithms
• C++ also provides STL algorithms implemented for vectors
• In order to use the algorithms, we need to include the algorithms
directive
• Some of the common algorithms are:
 sort(iterator1, iterator2): sort the elements of the vector starting from
position iterator1 (inclusive) up to iterator2 (exclusive)
 reverse(iterator1, iterator2): reverse the elements of the vector
starting from position iterator1 (inclusive) up to iterator2 (exclusive)
 *min_element(iterator1, iterator2): returns the iterator pointing to
the smallest element in the vector among the elements starting from
iterator1 up to iterator 2
 *max_element(iterator1, iterator2) similarly defined
 *find(iterator1, iterator2, search_value): searches the search_value in
the container starting from iterator1 (inclusive) up to iterator2
(exclusive) and returns an iterator to the first element in the range
that matches the search_value. If the search_value is not found, the
function returns iterator2.
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 29
Weldeselassie (Ph.D.)
C++ STL algorithms

Fraser International College CMPT135


Week 7 Lecture Notes Dr. Yonas T. 30
Weldeselassie (Ph.D.)
Concluding Remarks
• Of course we can not cover all the containers and
algorithms provided in the STL
• However the design concept among all the
containers is very similar with some specific
differences in the structure of the organization of
data in each container
• Also the algorithms have similar design concepts
• For more details see
http://www.cplusplus.com/reference/stl/
Fraser International College CMPT135
Week 7 Lecture Notes Dr. Yonas T. 31
Weldeselassie (Ph.D.)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy