Subscripts and Vectors


Subscripts in Vectors:

You can use the subscripts just like in arrays. The following is the method for using subscripts:

                    vector<int> intvec1;

intvec1.push_back(10);

                    intvec1.push_back(20);

                    intvec1[0] = intvec1[1] + 5;

After executing this piece of code, the vector intvec1 will contain 2 elements with the values 25 and 20.

Using subscripts in vectors helps in random access of the elements.


Boundary Checking in Vectors:

When you use subscripts to access vector elements boundary-checking is not performed. For example the following code fragment will cause a run-time error:

vector<int> intvec1;
vector<int>::const_iterator ptr;                         //declaring a constant iterator
intvec1.push_back(10);
intvec1.push_back(20);
intvec1[2]=30;                                                 //element does not exist
cout<<endl<<"Vector 1 now contains: ";
for (ptr=intvec1.begin( ); ptr!=intvec1.end( ); ptr++)
{
cout<<" "<<*ptr;
}

Since intvec1[2] does not exist the program will crash while running. While running the program does not check to see whether the value 2 is within the boundary limit of the vector. To prevent this problem we can make use of the member function ‘at’ for vectors.

Instead of

intvec1[2]=30;

we can use

intvec1.at(2)=30;

Now when the program is run, an exception will be thrown and this can be caught to prevent crashing. A simple program is illustrated below:

//Demonstrating the use of 'at' in vectors

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

int main( )
{
vector<int> intvec1;
vector<int>::const_iterator ptr;            
//declaring a constant iterator

intvec1.push_back(10);
intvec1.push_back(20);

try
{
intvec1.at(2)=30;
cout<<endl<<"Vector 1 now contains: ";

for (ptr=intvec1.begin( ); ptr!=intvec1.end( ); ptr++)
{
cout<<" "<<*ptr;
}

}

catch(out_of_range exc)
{
cout<<endl<<"EXCEEDED THE BOUNDARY OF VECTOR";
cout<<endl<<"PROGRAM TERMINATED";
cout<<endl<<exc.what( );
}

return 0;
}

The output will be:

EXCEEDED THE BOUNDARY OF VECTOR

PROGRAM TERMINATED

invalid vector<T> subscript

When this code:

        intvec1.at(2)=30;

is executed it will check the boundary limit of the vector. Since the vector currently has only 2 elements, it will throw an ‘out_of_range’ exception. By catching this you can prevent the program from crashing. In the above program ‘exc’ is an object of type out_of_range and it has a member function what( ).

        exc.what( );

This will give a short description about what caused the problem.


Learn more functions for vectors

Go back to Contents page 2.


Copyright © 2004 Sethu Subramanian All rights reserved.