STL Vector by ub40

Vector

  Vectors are sequential containers that are considered growable arrays, i.e., arrays that are flexible and grow as more data is inserted in them.

Vectors usually store elements in a contiguous linear memory space so that index-based access is performed efficiently. 

 

   When a vector’s originally allocated memory space is exceeded, a larger memory space is allocated and the existing data are copied into the new space before new elements are inserted. Memory allocated originally for the vector is then deallocated. Memory is usually allocated as multiples of machine’s page size to optimize performance, however, it may result in wasted space. Furthermore, frequent allocation, copying and deallocation can reduce the performance of a system using vectors. Vectors are, therefore, most suitable for data that requires fast (possibly index-based) access and relatively infrequent insertions. 

   Good points of discussion while attending an interview for a C++ Job, heh! 

   Anyways, following is a list of most frequently used methods and operators of the vector class,

 

Method

Description

vector()

Constructor, creates an empty vector.

vector(size_type n)

Constructor, creates a vector of n elements initialised to their default values.

T& back()

Returns a reference to the last element in the vector.

T& front()

Returns a reference to the first element in the vector.

void push_back(T& data)

Inserts a data value to the end of the vector.

void pop_back()

Erases the data value at the end of the vector.

size_type size()

Returns the number of elements contained in the vector.

T& operator[](int index)

Returns the reference to the index th element in the vector.

A few other methods related to iterators are discussed on the next section. The following example illustrates the use of a vector containing integers.

#include <iostream>
#include <vector>

using namespace std;

void populateVector(vector<int>& data, int* array, int arrayLen)
{
int i;
for (i=0;i<arrayLen;i++)
{
data.push_back(array[i]);
}
}

float getAverage(const vector<int>& data)
{
float sum = 0.0;
int i;
float average;
for (i=0;i<data.size();i++)
{
sum += data[i];
}
average = sum/data.size();
return average;
}

int main(void)
{
int intArray[] = {5, 7, 2, 3, 10};
vector<int> data;
float average;

cout << data.size() << " elements in the vector" << endl;
populateVector(data, intArray, sizeof(intArray)/sizeof(int));
cout << data.size() << " elements in the vector" << endl;
average = getAverage(data);
cout << "Average = " << average << endl;
return(0);
}

The output of this program is listed below,

0 elements in the vector
5 elements in the vector
Average = 5.4