Friday, September 18, 2009

Vector better than Array and works as Array

Vector is a template class and it allows programmers to create a dynamic array of elements of one type per instance.
  Vector is conceptually same as arrays in C. However, vector size can expand to hold more elements and can shrink when fewer will suffice.

Note: Accessing members of vector or appending elements does not depend on vector size and takes fixed amount of time, however, locating a specific value element or inserting value element into vector takes the amount of time directly proportional to its location in vector.

// Standard Template Library  (STL)
// Vector Functions:
// vector::push_back - Appends (inserts) an element to the end of a
// vector, allocating memory for it if necessary.
// vector::pop_back -  Erases the last element of the vector.
// vector::size - Returns number of elements in the vector.

#include <iostream>
#include <vector >

using namespace std ;

int main()
    // Dynamically allocated vector begins with 0 elements.
    vector<int> theVector;

    // Add one element to the end of the vector, an int with the value 1.
    // Allocate memory if necessary.
    theVector.push_back(1) ;

    // Add two more elements to the end of the vector.
    // theVector will contain [ 1, 2, 3 ].
    theVector.push_back(2) ;
    theVector.push_back(3) ;

    int tmp;

    cout << "\n Enter new element on new line. press Ctrl +D to terminate " <
    while (cin >> tmp)

    // Erase last element in the vector.

    // Print contents of theVector. 

    cout << "theVector [" ;
    for (int k =0; k < theVector.size(); k++)
      cout <<" " << theVector[k];
    cout << " ]" << endl ;

No comments:

Post a Comment