The following table shows some commonly used vector APIs:
|
API |
Description |
|
at ( int index ) |
This returns the value stored at the indexed position. It throws the std::out_of_range exception if the index is invalid. |
|
operator [ int index ] |
This returns the value stored at the indexed position. It is faster than at( int index ), since no bounds checking is performed by this function. |
|
front() |
This returns the first value stored in the vector. |
|
back() |
This returns the last value stored in the vector. |
|
empty() |
This returns true if the vector is empty, and false otherwise. |
|
size() |
This returns the number of values stored in the vector. |
|
reserve( int size ) |
This reserves the initial size of the vector. When the vector size has reached its capacity, an attempt to insert new values requires vector resizing. This makes the insertion consume O(N) runtime complexity. The reserve() method is a workaround for the issue described. |
|
capacity() |
This returns the total capacity of the vector, while the size is the actual value stored in the vector. |
|
clear() |
This clears all the values. |
|
push_back<data_type>( value ) |
This adds a new value at the end of the vector. |
It would be really fun and convenient to read and print to/from the vector using istream_iterator and ostream_iterator. The following code demonstrates the use of a vector:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main () {
vector<int> v;
cout << "\nType empty string to end the input once you are done feeding the vector" << endl;
cout << "\nEnter some numbers to feed the vector ..." << endl;
istream_iterator<int> start_input(cin);
istream_iterator<int> end_input;
copy ( start_input, end_input, back_inserter( v ) );
cout << "\nPrint the vector ..." << endl;
copy ( v.begin(), v.end(), ostream_iterator<int>(cout, "\t") );
cout << endl;
return 0;
}
Note that the output of the program is skipped, as the output depends on the input entered by you. Feel free to try the instructions on the command line.