More functions for Vectors


Using various functions available in Vectors:

//A program using various vector functions

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

//Function to display the contents of a vector
void display(vector<int> &vec)
{
vector<int>::const_iterator ptr;
for (ptr=vec.begin( ); ptr!=vec.end( ); ptr++)
{
cout<<" "<<*ptr;
}
}

int main( )
{
vector<int> intvec1;
int i;
intvec1.assign(4,7);
cout<<endl<<"After using assign: ";
display(intvec1);

for (i=1;i<5;i++)
{
intvec1.push_back(i);
}

cout<<endl<<"After pushing: ";
display(intvec1);

intvec1.pop_back( );
cout<<endl<<"After popping: ";
display(intvec1);

intvec1.erase(intvec1.begin());
cout<<endl<<"After erasing the first element: ";
display(intvec1);

cout<<endl<<"Capacity is: "<<intvec1.capacity();
intvec1.resize(17);
cout<<endl<<"Capacity after resizing: "<<intvec1.capacity();

cout<<endl<<"After resizing: ";
display(intvec1);

intvec1.assign(4,7);
cout<<endl<<"After using assign: ";
display(intvec1);

intvec1.clear( );
cout<<endl<<"After clearing: ";
display(intvec1);

return 0;
}

The output will be:

After using assign: 7 7 7 7
After pushing: 7 7 7 7 1 2 3 4
After popping: 7 7 7 7 1 2 3
After erasing the first element: 7 7 7 1 2 3
Capacity is: 8
Capacity after resizing: 17
After resizing: 7 7 7 1 2 3 0 0 0 0 0 0 0 0 0 0 0
After using assign: 7 7 7 7
After clearing:

There are 2 forms of the erase ( ) function. Either we can specify one iterator (this will erase that particular element) or you can specify a pair of iterators (this will erase all the elements in between these 2 iterators).

The resize( ) function can take 2 arguments. The first one specifies the capacity you want to allocate for the container and the second argument can be used to specify the values you want to initialize the elements to (by default this is 0 as illustrated in the program above).


Go to the section on STL Lists

Go back to Contents page 2.


Copyright © 2004 Sethu Subramanian All rights reserved.