Industrial Training

Stl



One of the basic classes implemented by the Standard Template Library is the vector class. A vector is, essentially, a resizeable array; the vector class allows random access via the [] operator, but adding an element anywhere but to the end of a vector causes some overhead as all of the elements are shuffled around to fit them correctly into memory. Fortunately, the memory requirements are equivalent to those of a normal array. The header file for the STL vector library is vector. (Note that when using C++, header files drop the .h; for C header files - e.g. stdlib.h - you should still include the .h.) Moreover, the vector class is part of the std namespace, so you must either prefix all references to the vector template with std:: or include "using namespace std;" at the top of your programVectors are more powerful than arrays because the number of functions that are available for accessing and modifying vectors. Unfortunately, the [] operator still does not provide bounds checking. There is an alternative way of accessing the vector, using the function at, which does provide bounds checking at an additional cost. Let's take a look at several functions provided by the vector class:.

unsigned int size();            Returns the number of elements in a vector
push_back(type element);        Adds an element to the end of a vector
bool empty();                   Returns true if the vector is empty
void clear();                   Erases all elements of the vector
type at(int n);                 Returns the element at index n, with bounds checking

also, there are several basic operators defined for the vector class:

=           Assignment replaces a vector's contents with the contents of another
==          An element by element comparison of two vectors
[]          Random access to an element of a vector (usage is similar to that
            of the operator with arrays.) Keep in mind that it does not provide
            bounds checking.

Let's take a look at an example program using the vector class:

#include <iostream>
#include <vector>
 
using namespace std;
int main()
{
    vector <int> example;         //Vector to store integers
    example.push_back(3);         //Add 3 onto the vector
    example.push_back(10);        //Add 10 to the end
    example.push_back(33);        //Add 33 to the end
    for(int x=0; x<example.size(); x++) 
    {
        cout<<example[x]<<" ";    //Should output: 3 10 33
    }
    if(!example.empty())          //Checks if empty
        example.clear();          //Clears vector
    vector <int> another_vector;  //Creates another vector to store integers
    another_vector.push_back(10); //Adds to end of vector
    example.push_back(10);        //Same
    if(example==another_vector)   //To show testing equality
    {
        example.push_back(20); 
    }
    for(int y=0; y<example.size(); y++)
    {
        cout<<example[y]<<" ";    //Should output 10 20
    }
    return 0;
}
Hi I am Pluto.