The vector container resembles a C++ array in that it holds zero or more objects of the same type, and that each of these objects can be accessed individually. (Be sure to study the requirements for objects that are stored in STL containers.) The vector container is defined as a template class, meaning that it can be customized to hold objects of any type. Here is a simple example:
#include <vector> using namespace std; ... // Define a vector of integers. // The template name is "vector" and the type of object // it contains is "int"; the fully specified container // data type is "vector<int>". vector<int> vec_one; int a = 2; // Some integer data objects int b = -5; vec_one.push_back(a); // Add item at end of vector vec_one.push_back(9); vec_one.push_back(b); // vec_one now contains three int values: 2, 9, -5 unsigned int indx; for (indx = 0; indx < vec_one.size(); indx++) { cout << vec_one[indx] << endl; Write out vector item } |
Some commonly used member functions of the vector class are:
size |
size_type size() const; |
empty |
bool empty() const; |
push_back |
void push_back(const T& x); |
begin |
iterator begin(); |
end |
iterator end(); |
void erase(iterator first, iterator last); vector<int> a; ... a.erase(a.begin(),a.end()); // Remove all elements. |
|
clear | void clear (); vector<int> a; |
---|
Some of the operators defined for the vector container are:
= |
The assignment operator replaces the target vector's contents with that of the source vector: vector<int> a; vector<int> b; a.push_back(5); a.push_back(10); b.push_back(3); b = a; // The vector b now contains two elements: 5, 10 |
== |
Tests whether two vectors have the same content (element-by-element comparison for all elements). |
[] |
The subscript operator returns a reference to an element of the vector. A subscript value of zero returns a reference to the first element, and so on. The subscript must be between zero and size()-1. See the example above to see how the subscript operator is used in a loop to access elements of a vector. The subscripted vector may appear on the left or right sides of an assignment (the returned reference is an lvalue): vector<double> vec; vec.push_back(1.2); vec.push_back(4.5); vec[1] = vec[0] + 5.0; vec[0] = 2.7; // Vector now has two elements: 2.7, 6.2 |
To sort a vector, see the STL sort algorithm.
Copyright 2002 by Patrick Meier
Last updated on 26.08.2002 by Patrick Meier