Thursday, November 10, 2011

vectors in c++


stl vector / vector in stl

A vector manages its elements in a dynamic array. It enables random access, which means you can access each element directly with the corresponding index. Appending and removing elements at the end of the array is very fast. However, inserting an element in the middle or at the beginning of the array takes time because all the following elements have to be moved to make room for it while maintaining the order.

Note: Strictly speaking, appending elements is amortized very fast. An individual append may be slow, when a vector has to reallocate new memory and to copy existing elements into the new memory. However, because such reallocations are rather rare, the operation is very fast in the long term.

The following example defines a vector for integer values, inserts six elements, and prints the elements of the vector:

// stl/vector1.cpp
#include <iostream>
#include <vector>

using namespace std;

int main() {
   vector<int> coll; //vector container for integer elements
   // append elements with values 1 to 6
   for (int i=1; i<=6; ++i) {
      coll.push_back(i);
   }
   //print all elements followed by a space
   for (int i=0; i<coll.size( ); ++i) {
      cout << coll[i] << ' ';
   }
   cout << endl;
}

With

#include <vector>

the header file for vectors is included. The declaration

vector<int> coll;

creates a vector for elements of type int. The vector is not initialized by any value, so the default constructor creates it as an empty collection.

The push_back() function appends an element to the container:

coll.push_back(i);

This member function is provided for all sequence containers. 

The size() member function returns the number of elements of a container:

for (int i=0; i<coll.size(); ++i) {
   ...
}
This function is provided for any container class.

By using the subscript operator [], you can access a single element of a vector:

cout << coll[i] << ' ';

/*
 * OUTPUT
 */
Here the elements are written to the standard output, so the output of the whole program is as follows:

1 2 3 4 5 6
See Also:

No comments:

Post a Comment