You are on page 1of 42

CO1401

Programming

Week 9
STL & Vector Class
The module

• The module has gone through all of the basic material for
C++.
• If you are struggling with the module then concentrate on
the material I've already covered: Weeks 1 - 5.
• Go to Laurent’s and Oliver’s sessions!
• The rest of the module includes practice. Treat the rest of
the module as practice material. You do not need it to
complete the assignment to a first.
• The rest of the module is important:
• Important bits of C++.
• Leads directly into Advanced C++ next year.
• Can be used in the assignment.
2 Programming
Topic 1

The STL

3 Programming
The Standard Template Library (STL)

• The Standard Template Library (STL) is a library which


implements commonly used data structures and data
objects.
• The STL container classes have a similar interface.
They share a common syntax.
Generic programming

• We have been using arrays.


• If you use an array you, obviously, need to supply the
data type.
• However, many of the things you've been doing with
arrays are always the same, irrespective of the data
type.
• For example, consider displaying the contents of an
array or a function to place an item into an array.
Generic programming

void Insert( int intArray[], int val, int index )


{
intArray[index] = val;
}

void Display( int intArray[] )


{
for(int i =0; i < SIZE; i++ )
{
cout << intArray[i] << " ";
}
}
Generic programming

void Insert( float floatArray[], float val, int i )


{
floatArray[i] = val;
}

void Display( float myFloatArray[] )


{
for(int i = 0; i < SIZE; i++ )
{
cout << floatArray[i] << " ";
}
}
Generic programming

• The data type had no relevance to the operation.


• Generic programming is programming with some sort
of "to be specified later" data type. The way in which
generic programming is implemented in C++ is
through the use of templates. Hence, the Standard
Template Library.
• The STL is a library built using templates. The actual
code is generated at compile-time. So a version to
match whatever data type you are using is created
when you compile the program.
Abstract Data Type

• The STL is also connected with the theory of Abstract


Data Types (ADT).
• It is possible to model the operations and the data
without needing to reference the actual data.
• For example, a stack of integers, a stack of strings, a
stack of structures.
• The last example is important, we've the ability to
create new data types so we want a method that is
open and which will cope with any new data type we
create.
• Abstract Data Type is a model of data objects and the
operations upon them. The data type is irrelevant.
Abstract Data Type

• Consider an array
• We can add an item to the array
• We can remove an item from the array
• We can move through each element of the array
• We use an index (for example a loop and an index
to go through each element of the array)
• We can look at the values stored in the array.
The STL

• There are a number of data structures which are well


known and which are used time and time again.
• For example, stacks, linked list, queues.
• The precise details of these data structures are out of
the scope of this module: see the Advanced C++ next
year
• For our immediate purposes we only need to know
that the STL will provide a safe alternative to arrays,
and that it provides many of the operations we will
want to use.
The STL - overview

• The Standard Template Library contains four things:


• Container. A container is a data structure or ADT
which we can use to store objects.
• Iterators. An object that allows us to go through a
container.
• Algorithms. Common algorithms such as sort.
• Functors. Advanced: Classes which overload the
function operator.
• The STL uses classes. A class combines data and the
methods associated with the data. The methods are
operations which we use with, or upon, the data.
The STL container classes

• There are several categories of containers.


• The different container classes have different
capabilities and performance. This is a reflection of
the abstract data types and their computational
complexity.
• For example, vector provides rapid insertions and
deletions at back, whilst deque provides rapid
insertions and deletions at front or back.
• As another example, stack is last-in, first-out (LIFO)
whist queue is first-in, first-out (FIFO).
Advantages

• Robust and debugged. The first release had problems.


This is no longer the case. The suggestion that the STL
nowadays is buggy or slow is simply false.
• Fast. Defined as inline templates for speed.
• You are safer using the STL than defining your own
classes. It is debugged, your own code is not.
• Saves production time. For example, quicker to use
the list class than to build your own.
Disadvantages

• Debugging can be very difficult, especially with STL


classes that contain or reference other STL classes.
• May not suit all purposes, e.g. containers which hold
other containers.
Conclusion

• You should use the STL.


• This module will introduce the vector class.
• You should experiment with the other classes in the
STL.
• The STL will save you time.
• The STL will produce more robust code.
Topic 2

Containers
(using the vector class)

17 Programming
STL

• For the current lecture we're going to concentrate on


two things:
• containers
• iterators.
• I'm going to use the vector class.
• For further information about the STL container
classes see MSDN:
• https://msdn.microsoft.com/en-
us/library/9xd04bzs.aspx

18 Programming
Vector

• The vector class is one of the container classes. The


container classes contain data, e.g. a simple data type such
as integer, or a more complex data type such as a class.
• It has nothing to do with the mathematical term "vector".
• Include the <vector> library.
• Use the keyword vector.
• You provide the data type that the vector is going to store
(what it "contains"). This is placed inside left and right
chevrons.
• You provide the name of the vector, i.e. the variable name.
• You provide the size of the vector in round brackets.

19 Programming
Vector

#include <vector>
using namespace std;

int main()
{
vector <int> v(15); // vector of ints
vector <float> f(5);
// vector of floats
}

20 Programming
Vector

• Can create a vector with a size, the same way that you
would with an array:

// size 10 vector of ints


vector <int> v( 10 );

• This has created a vector called "v". It stores integers.


It can store 10 integers.
• Indexing starts at 0.

21 Programming
Referencing vector elements

• Use the name of the vector, followed by the subscript


in square brackets:

vector <float> rainfall( 100 );


rainfall[22] = 37.2f;
cin >> rainfall[22];
if( rainfall[22] > maximum )
{
maximum = rainfall[22];
}

22 Programming
Vector boundaries

23 Programming
Vector boundaries

• If you compile in debug mode then out of bounds


errors will be caught and you get an informative error
message.
• The following code will cause an error:

vector <int> v(4);


cout << v[4] << endl;

24 Programming
Vector: size

• Vectors are a class.


• They have methods which you can use.
• Use the dot operator with the variable name.
• For example, the method size returns the size of the
vector.

vector <int> v(4);


cout << v.size( ) << endl;

25 Programming
Vector: loop using size

• This makes vector easier to use than arrays:


vector <int> v(4);
v[0] = 3;
v[1] = 5;
v[2] = 1;
v[3] = 2;

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


{
cout << v[i];
}
26 Programming
Vector: front, back, empty

• Can directly return the values at the beginning of the


vector:
int i = v.front( );

• Note you cannot assign a value to the


vector using front (or back).

• Can directly return the values at the beginning of the


vector
int i = v.back( );

27 Programming
Vector: empty

• Can use empty to check wet he the vector is empty:


if( !v.empty() )
{
// vector is not empty
}

28 Programming
Vector: at

• The at() function returns the value held at a location.

cout << v.at( 2 );

• If the at() function is used then out of bound errors


are automatically detected.
• However, what it does is "throw" an out of bounds
error: see the Advanced C++ next year
Other methods

• A full list and description of the methods together


with examples of use can be found on MSDN:
• http://msdn.microsoft.com/en-
us/library/k449z507.aspx

• clear
• erase
• insert
The vector class: dynamic

• The vector class is a dynamic array.


• It can be dynamically resized. In programming
"dynamic" means whilst the programming is running.
vector <int> v(2);
v.resize( 4 );
v[2] = 1;

• You may lose data is you resize it downwards!


v.resize( 2 );
push: dynamic expansion

• Possibly the most convenient thing about vectors is the


way in which we can dynamically increase the vector
by putting a new value onto the beginning or end of
the array.
vector <int> v(2);
v[0] = 3;
v[1] = 5;
v.push_back( 4 );
cout << v.size( ); // size is now 3
cout << v[2]; // 3rd element, i.e. back
cout << v.back( ); // back of vector
push: dynamic expansion

• Can start with an empty list.


int i;
vector <int> v;
cout << "Enter number";
cin >> i;
v.push_back( i );

• This is a safe and easy way to create an array of


objects.
• I could combine this with a loop, or a file read, and so
on ...
push: dynamic expansion

• Can push onto the end of the list:

v.push_back( 10 );

• Can push onto the front of the list:

v.push_front( 25);
vectors and functions

• Can pass a vector to a function.


• This version is not efficient because it uses call by copy.

// correct, but inefficient


void DisplayVector( vector <int> v )
{
for( int i = 0; i< v.size(); i++ )
{
cout << v[i] << " ";
}
cout << endl;
}
vectors and functions

• Faster to use a reference parameter.

// correct and more efficient


void DisplayVector( vector <int>& v )
{
for( int i = 0; i< v.size(); i++ )
{
cout << v[i] << " ";
}
cout << endl;
}
vectors and functions

• Invoke the function in the normal way:

int main()
{
vector <int> v( 3 );
v[0] = 2;
v[1] = 5;
v[2] = 7;

DisplayVector( v );
}
Topic 3

Iterators

38 Programming
Iterators

• An alternative to the use of indices and the [ ]


operator.
• The iterator points at a container, i.e. the iterator
points at an element of the vector.
• The iterator be can be made to point at the beginning
of the vector.
• The iterator can be advanced through the list of
container using the increment (++) operator.
• Advanced: an iterator is a generalisation of a pointer.
Iterators

• Use the keyword iterator.


• Iterators are common to all of the container classes
and the syntax is the same for all of them.
• begin: returns an iterator to the start of the vector
• end: returns an iterator past the end of the vector.
• The iterator is moved through the vector in much the
same fashion as an array index.
• Can use the increment operator.
Iterators

vector <int> v( 10 );
vector <int>::iterator it;

for( it = v.begin(); it != v.end(); it++ )


{
cout << *it << " ";
}
Summary

• Use the <vector> library


• A dynamic array
• Can resize whilst the program is running
• Can dynamically add new value and the location to
store them using push_front and push_back.
• Can use the array syntax of angled brackets []
• Can also use iterators.

You might also like