Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views14 pages

Chapter 8 Vectors

The document discusses the concept of vectors as dynamic containers in C++, part of the Standard Template Library (STL). It explains how vectors differ from arrays, their advantages, and provides details on declaring, initializing, and manipulating vectors. Additionally, it includes example code for using vectors to compute an average of user-inputted integers.

Uploaded by

S'fiso Mzilikazi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views14 pages

Chapter 8 Vectors

The document discusses the concept of vectors as dynamic containers in C++, part of the Standard Template Library (STL). It explains how vectors differ from arrays, their advantages, and provides details on declaring, initializing, and manipulating vectors. Additionally, it includes example code for using vectors to compute an average of user-inputted integers.

Uploaded by

S'fiso Mzilikazi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

VECTORS AS CONTAINERS

 A container is an object that can contain other objects.


 The class vector is defined in the Standard Template Library (STL) for C++.
 The STL vector container is implemented using a template class (templates
are covered in Chapter 17).
THE STANDARD TEMPLATE
LIBRARY (STL)
 The Standard Template Library (STL) standardises commonly used components
through a set of containers (lists, vectors, sets, maps, etc.) that hold objects,
built-in objects and class objects.
 The containers keep the objects secure and define a standard interface to
manipulate them.
 The STL also contains standard algorithms that can be applied to the objects
while they are in the container, for instance, to sort them, compare them,
merge objects into another container, find a specific object and many more
operations.
 The STL algorithms use iterators, which are similar to pointers, to operate on
the objects in the containers.
 The algorithms manipulate the objects in a standard way and the iterators
ensure that the algorithms handle all and only the elements in the containers,
and no more.
NOTE:: For this module, you do not need to be able to use the iterator access
methods for vectors.
VECTORS
 Vectors can be considered to be a generalization of the built-in array type.
 Arrays have a fixed length.
 The length of an array cannot be changed when the program is running.
 Vectors can be thought of as arrays that can grow (and shrink) in length as
needed while your program is running. i.e vectors do not have a fixed size.
 If more capacity is needed to store additional elements, the capacity is
automatically increased
 Like arrays:
 A vector stores a collection of values of its base type.
 Elements are indexed by integer keys, starting at 0.
 Square bracket notation can be used to read or change these elements e.g.
vect[i]. N.B. [] cannot be used to initialize an item – only to change an element
that has already been assigned a value.
ADVANTAGES OF USING
VECTORS
 The size of a vector need not be fixed and can be changed during
program execution.
 Individual elements in a vector can be directly indexed (using an
iterator) – important when you need to rapidly access arbitrary
elements.
 Can store multiple objects.
 Dynamic size avoids memory wastage.
 Memory allocation and deallocation are handled automatically.

https://www.geeksforgeeks.org/advantages-of-vector-over-array-in-c/
DECLARING A VECTOR
 To use a vector, we need to include:
 the correct header file that contains the declarations of the vector class
and
 make the names from the standard namespace available

#include <vector>
using namespace std;
DECLARING A VECTOR
 General format of vector declaration:
Template class – produces
a class for vectors with
any base type that you
vector <Base_Type>
plug into it.

 Declaration of a vector with a base type int:

vector<int> v;
Class Identifier (variable name)

Data type of items


to be stored
INITIALIZING A VECTOR
 Note: The notation vector <int> is a class name.

The declaration of v as a vector of type vector <int> therefore:

 Includes a call to the default constructor for the class vector <int>
 Creates a vector object that is empty (has no elements).
SIZE OF A VECTOR
 We can initialize the number of items by using a vector constructor
which takes one integer as the argument. For example,
vector<int> sample(10);
 The first 10 elements of the vector sample will be initialized to 0.
 The statement:
cout << sample.size( );
will display a size of 10.
 Once the vector has been initialized, you can use the [] to set
other values for these elements. For example:
for(int i = 0; i < v.size( ); i++)
v[i] = 2*i;
ADDING ITEMS TO A VECTOR
 Use the push_back function to add an item to a vector. The
function push_back will add an element in the next available position.
 Example:
vector<double> sample;
sample.push_back(0.0);
sample.push_back(1.1);
sample.push_back(2.2);
 These lines initialize the elements 0, 1, and 2 of the vector called sample
to 0.0, 1.1, and 2.2 respectively.

0 1 2 Index – location of item


0.0 1.1 2.2 Actual item stored in that
location
SIZE OF A VECTOR
 The size of a vector is the number of elements in
that vector.
 The member function size( ) is used to determine
the size of a vector.
 For example cout << sample.size( ); will return the
number of items that we have stored in sample.
 The size function returns an unsigned int, because
the returned value should always be positive.
CAPACITY OF A VECTOR
 At any point in time a vector has a capacity.
 The capacity of a vector refers to the number of vector
elements for which it currently has memory allocated.
 To determine the capacity of a vector, use the
capacity( ) function.
e.g. cout << v.capacity( );
 Whenever a vector runs out of capacity and needs room for
an additional member, the capacity is automatically
increased. The increase is usually done by doubling the
existing capacity, but this may not be efficient.
CAPACITY OF A VECTOR
 There are two other functions that can be used to change the capacity
of a vector.
 reserve(Limit) will explicitly increase the capacity by Limit. For
example:
v.reserve(32);
will set the capacity to at least 32 elements.
 Note that the reserve( ) function can increase the capacity but may
not be able to decrease the capacity.
 You can reduce the capacity using the resize function:
v.resize(24);
resizes the vector to 24 elements.
TRY IT YOURSELF
 Program using a vector to read values and to compute their average.

#include<iostream>
#include<vector>
using namespace std;
int main( )
{
vector<int> v(4);
char ans = 'y';
float sum = 0;
int count = 0;
while(ans == 'y' || ans == 'Y')
{
cout << "Enter an integer \n";
cin >> v[count];
sum += v[count];
count++;
cout << "Do you wish to enter a new number y/n \n";
cin >> ans;
}
if(count > 0)
{
cout << "Average of " << count << " numbers is " << sum/count << endl;
}
return 0;
}
TRY IT YOURSELF
 Copy and paste or carefully type the code in the previous slide and compile it. Run the program
for the following cases:
 4 numbers: 2 2 2 2 the average in this case is 2
 6 numbers: 2 2 2 2 2 2 the average is 2 again
 8 numbers: 1 2 3 4 5 6 7 8 the average in this case is 4.5
 Did you get the correct answers?
 Replace the i in the statement sum/count with one of the v.size( ) or v.capacity( ) that you think
should produce the correct results.
 Compile and run the program for the above three cases.
 Did you get the correct results in all three cases?
 Can you explain the reason for not getting the correct answer?

You might also like