http://cpp.gantep.edu.tr
C++ resources. Faculty of Engineering, University of Gaziantep
 MAIN  -  Tutorials  -  Howtos  -  nmPrimer  -  Misc  -  Links  -  Contacts
C++ Tutorial (Basic)
[index][<][1][2][3][4][5][6][7][8][9][>]

8. Vectors

Last modified: Wed, 13 Apr 2011 17:30:13 +0300

Complete: ################---- (80%)

8.1 Introduction
8.2 Declaring and Initialising Vectors
8.3 Vector Manipulation
8.4 Member Functions of the Vector Class
8.5 Examples
8.6 Exercises

8.1 Introduction

As for arrays, vectors contain lists of values (elements) that are referenced with an index. The elements of a vector can be processed in the same way as those of an array. However, a vector is a class template in the C++ Standard Template Library and so in addition to basic array processing the programmer has access to many member functions that provide easy and powerful vector processing. A notable advantage of vectors over arrays is the ability to easily add or remove elements thus allowing more effective management of the elements and efficient management of computer memory.

In this section of the tutorial, vectors will be introduced at a very basic level. The discussion of member functions will be very limited as this topic more properly belongs to a section on Classes that can be found in the advanced tutorial.

8.2 Declaring and Initialising Vectors

To use vectors in a program, the following header must be included in the source code:

  #include <vector> 
There are various ways to declare and initialise a vector. For example the statement:
  vector<elemType> sv(n);
creates a vector sv of type elemType with n elements. The value of each vector element is automatically assigned to zero. Alternatively declaration and initialisation can be done at the same time as in the following statement:
  vector<elemType> sv(n,value);
This creates a vector sv with all n elements set to value. As with arrays, the subscripts of vector elements are given inside square brackets. Consider the following sample program.

08prg01.cpp: Declaring and initialising vectors
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
// Declaring and initialising vectors
#include <iostream>
#include <vector>
using namespace std;

int main()
{

  vector<int> sv1(5), sv2(5,12);

  for (int j=0; j<5 ; j++)
  {
    sv1[j] = j*2;

    cout << "  sv1(" << j << ") = " << sv1[j]
         << "  sv2(" << j << ") = " << sv2[j]
         << endl;
  }

  return 0;

}
  sv1(0) = 0  sv2(0) = 12
  sv1(1) = 2  sv2(1) = 12
  sv1(2) = 4  sv2(2) = 12
  sv1(3) = 6  sv2(3) = 12
  sv1(4) = 8  sv2(4) = 12

In this program, the statement vector<int> sv1(5), sv2(5,12); declares type integer vectors sv1 and sv2 both with five elements. The value of each element of vector sv1 is assigned in the loop while the elements of vector sv2 are assigned the value 12 during declaration. You can see from the output of the program that the subscripts of vectors start with 0 (as is the case for arrays).

8.3 Vector Manipulation

As for arrays and ordinary variables, the elements of a vector can be used in arithmetic operations. For example,

  vector<double> dv(3);
  dv[0] = 2.4;
  dv[1] = -1.3;
  dv[2] = dv[0]+dv[1];
In this case the value of element dv[2] is 1.1. Vector elements can can be also used in selection structures; for example in the preceeding example we can append:
  if ( dv[2] < dv[0] ) dv[2] *= 2;  
The value of dv[2] is updated as 2.2.

The equivalence of processing arays and vectors is exemplified in the following program where the sum of the product of the elements of two different vectors is calculated.

08prg02.cpp: Manipulation of vector elements
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
 24:
 25:
 26:
 27:
 28:
 29:
 30:
 31:
// manipulation of vector elements
#include <iostream>
#include <vector>
using namespace std;

int main()
{

  float prod=0;
  vector<float> v1(10), v2(10);

  for(int i=0;i<10;i++)
  {

    v1[i] = 1.2*i;
    v2[i] = i+2.5;

    prod = prod + v1[i]*v2[i];

    cout << " v1(" << i << ") = " << v1[i]
         << "\tv2(" << i << ") = " << v2[i]
         << "\tv1(" << i << ")*v2(" << i << ") = "
         << v1[i]*v2[i] << endl;
  }

  cout << "The sum of the product of "
       << "v1 and v2 elements is " << prod << endl;

  return 0;

}
 v1(0) = 0	v2(0) = 2.5	v1(0)*v2(0) = 0
 v1(1) = 1.2	v2(1) = 3.5	v1(1)*v2(1) = 4.2
 v1(2) = 2.4	v2(2) = 4.5	v1(2)*v2(2) = 10.8
 v1(3) = 3.6	v2(3) = 5.5	v1(3)*v2(3) = 19.8
 v1(4) = 4.8	v2(4) = 6.5	v1(4)*v2(4) = 31.2
 v1(5) = 6	v2(5) = 7.5	v1(5)*v2(5) = 45
 v1(6) = 7.2	v2(6) = 8.5	v1(6)*v2(6) = 61.2
 v1(7) = 8.4	v2(7) = 9.5	v1(7)*v2(7) = 79.8
 v1(8) = 9.6	v2(8) = 10.5	v1(8)*v2(8) = 100.8
 v1(9) = 10.8	v2(9) = 11.5	v1(9)*v2(9) = 124.2
The sum of the product of v1 and v2 elements is 477

8.4 Member Functions of the Vector Class

The vector class has many useful member functions (methods) providing simple and powerful vector processing.
In this section some basic member functions will be introduced. A much broader reference can be obtained by following the links below.

Note that many member functions reference the elements of a vector via an iterator instead of a normal integer. This will be discussed only very breifly in this section.

An important operation is to be able to add or remove elements from a vector. This can be acheived using the push_back() and pop_back() functions respectively. Note that the word "pop" can be considered to mean "pull" in this context.

For example consider the type integer vector iv declared with 3 elements initialised with 2 as follows:

  vector<int> iv(3,2);
This vector can be represented as follows:
vectoriv
element012
value222
We can add two more elements as follows:
  iv.push_back(15);
  iv.push_back(35);
The vector is now:
vectoriv
element01234
value2221535
We can remove the last element with:
  iv.pop_back();
The vector is now:
vectoriv
element0123
value22215
Using the vector class is one method of constructing a dynamic array, i.e. it's size can be defined and modified at run-time. Note that we cannot perform such operations on normal arrays; such arrays are called static with the size defined and fixed at compile-time.

The vector class includes many other member functions. Some of them are listed below:

iv.size()Returns the number of elements in vector iv (including zero for an empty vector).
iv.resize(num)Changes the number of elements in vector iv to num (the vector can expand or truncate).
iv.clear()Deletes all elements in vector iv leaving it empty (but still declared).
iv.empty()Returns true if the vector iv is empty, false otherwise.
These four member functions plus push.back() and pop.back() are illustrated in the program below which also exemplifies passing a vector to a function:

08prg03.cpp: Vector member functions
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
 24:
 25:
 26:
 27:
// Vector member functions
#include <iostream>
#include <vector>
using namespace std;

void vecStatus(vector<int>);

int main()
{
  vector<int> vec(3,2);  vecStatus(vec);
  vec.push_back(15);     vecStatus(vec);
  vec.push_back(35);     vecStatus(vec);
  vec.pop_back();        vecStatus(vec);
  vec.resize(8);         vecStatus(vec);
  vec.clear();           vecStatus(vec);
  vec.resize(6);         vecStatus(vec);
}

void vecStatus(vector<int> v) {
  if ( v.empty() ) cout << "vec is empty." << endl;
  else {
    cout << "vec has " << v.size() << " elements: ";
    for (unsigned int i=0; i<v.size(); i++)
      cout << v[i] << " ";
    cout << endl;
  }
}
vec has 3 elements: 2 2 2
vec has 4 elements: 2 2 2 15
vec has 5 elements: 2 2 2 15 35
vec has 4 elements: 2 2 2 15
vec has 8 elements: 2 2 2 15 0 0 0 0
vec is empty.
vec has 6 elements: 0 0 0 0 0 0

Note the use of the void function vecStatus() to report the size and content of the vector as it evolves.

In the following functions, parameters i, j and k are iterators instead of normal integers:

iv.insert(i,x)Value x is inserted into vector iv at position i.
iv.erase(j,k)Deletes all elements of vector iv between j and k.
These member functions are illustrated in the program below. This program uses the functions begin() and end() that return iterators pointing to the first and last element of the vector respectively.

08prg04.cpp: Vector member functions with iterators
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
 24:
 25:
 26:
 27:
// Vector member functions with iterators
#include <iostream>
#include <vector>
using namespace std;

void vecStatus(vector<double>);

int main()
{
  vector<double> vec(6);
  for ( unsigned int i=0; i<vec.size(); i++ )
    vec[i]=1.1*(i+1);
                                           vecStatus(vec);
  vec.insert(vec.begin(),   0.8);          vecStatus(vec);
  vec.insert(vec.begin()+4, 3.7);          vecStatus(vec);
  vec.erase( vec.begin()+3, vec.end()-2 ); vecStatus(vec);
}

void vecStatus(vector<double> v) {
  if ( v.empty() ) cout << "vec is empty." << endl;
  else {
    cout << "vec has " << v.size() << " elements: ";
    for (unsigned int i=0; i<v.size(); i++)
      cout << v[i] << " ";
    cout << endl;
  }
}
vec has 6 elements: 1.1 2.2 3.3 4.4 5.5 6.6 
vec has 7 elements: 0.8 1.1 2.2 3.3 4.4 5.5 6.6 
vec has 8 elements: 0.8 1.1 2.2 3.3 3.7 4.4 5.5 6.6 
vec has 5 elements: 0.8 1.1 2.2 5.5 6.6 

Finally, this section has provided just a short introduction to vectors. Remember that there are many more powerful member functions and algorithms; to use these fully you need to understand iterators. See the links provided above and the relevant section in the advanced tutorial.

8.5 Examples

The following program creates a vector of integer values and calculates their mean. Then elements that have a value less than the mean are removed from the vector.

08prg05.cpp: Example use of vectors
  1:
  2:
  3:
  4:
  5:
  6:
  7:
  8:
  9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
 24:
 25:
 26:
 27:
 28:
 29:
 30:
 31:
 32:
 33:
 34:
 35:
 36:
 37:
 38:
 39:
 40:
 41:
 42:
 43:
 44:
 45:
 46:
 47:
// Example use of vectors
// The mean of a  vector  of  10 integer values  is
// calculated, then elements that have a value less
// than the mean are removed from the vector.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{

    unsigned int i, sum=0;
    vector<int> iv;

    // Push arbitrary values to the vector
    for ( i=10; i<20; i++ ) {
      int k = i*(i+8) % 30;
      iv.push_back(k);
    }

    // Show the vector
    cout << "Vector iv = ";
    for( i=0; i<iv.size(); i++ ) cout << iv[i] << " ";
    cout << endl;

    // Calculate the mean of the values
    for( i=0; i<iv.size(); i++ ) sum = sum + iv[i];
    double mean = double(sum) / iv.size();

    // Remove elements that have values less than the mean
    cout << "Removing values less than " << mean << endl;
    for ( i=0; i<iv.size(); i++ ) {
      if ( iv[i] < mean ) {
        iv.erase( iv.begin()+i );
        i--;
      }
    }

    // Show the reduced vector
    cout << "Vector iv = ";
    for( i=0; i<iv.size(); i++ ) cout << iv[i] << " ";
    cout << endl;

    return 0;
}
Vector iv = 0 29 0 3 8 15 24 5 18 3 
Removing values less than 10.5
Vector iv = 29 15 24 18 

8.6 Exercises

  1. Write a program that includes a vector with the following elements; A={3,5,-2,4,7}, then add two more elements with values 10 and 12 to the end of the vector.

  2. A vector is given as follows: B={3,-5,-2,4,-7,9,22,-8}. Write a program to remove the negative elements from the vector.

  3. Write a program that reads the elements of a vector of initial size n. Then insert the mean of the elements to the end of the vector.

  4. Write a program that creates a vector containing all prime numbers between 1 and 500.
    See http://en.wikipedia.org/wiki/Prime_number
    and http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
[index][<][1][2][3][4][5][6][7][8][9][>]
please send us you comments/questions/corrections