Definition
The vector template is defined in the standard header <vector>, and in the nonstandard backward-compatibility header <vector.h>.
#include <vector>
namespace std {
template <class T, class Allocator=allocator<T>>
class vector;
}
Description
A vector is a Sequence that manages a dynamic array whose elements are of any type T that are both assignable and copyable.
A simple example of creating a vector is:
std::vector<int> a; // creates an empty vector of integer type
std::vector<float> b(10); // create a vector with 10 float types.
With access to the vector contains performed in the usual C way:
std::cout<<a[0]<<std::endl;
std::cout<<b[2]<<std::endl;
The optional second parameter defines the memory model, which by default is an allocator.
Vectors copy their elements into their internal dynamic array, whose elements are ordered. Vectors provide constant time random access to all of the data. The iterators are also random access iterators, therefore vectors can be used with any algorithm within STL.
Vectors provide good performance if you append (or delete) elements from the end of the container. If you insert or delete from any other position then the performance is poor, with every element after the insertion or deletion point being moved to maintain an ordered and continuous array of elements.
Size and Capacity
One way vectors achieve good performance is to allocate more memory than then actually need for the purpose.
To avoid reallocation you can use the reserve command when you instantiate the container, i.e.
std::vector<int> v;
v.reserve(80); // reserve memory for 80 elements
this is equivalent to
std::vector<T> v(80);
Vector Operations
Create, Copy and Destroy Operations
| Operation | Effect |
| vector< El > c | Creates an empty vector without any elements |
| vector< El > c1(c2) | Creates a copy of another vector of the same type |
| vector< El > c(n) | Creates a vector with n elements that are created using the default constructor of El |
| vector< El > c(n,el) | Creates a vector initialized with n copies of element el |
| vector< El > c(begin,end) | Creates a vector initialized with the elements from another container, defined by its iterators (begin, end) |
| c.~vector< El >() | Destroys all elements and frees the memory |
Nonmodifying Operations
| Operation | Effect |
| c.size() | Returns the actual number of elements in the container |
| c.empty() | Returns if the container is empty |
| c.max_size() | Returns the maximum number of possible elements |
| capacity() | Returns the maximum possible number of elements without memory reallocation |
| reserve() | Enlarges the current max capacity of the container |
| c1==c2 | Returns if c1 is equal to c2 |
| c1!=c2 | Returns if c1 is not equal to c2 |
| c1<c2 | Returns if c1 is less than c2 |
| c1>c2 | Returns if c1 is greater than c2 |
| c1<=c2 | Returns if c1 is less than or equal to c2 |
| c1>=c2 | Returns if c1 is greater than or equal to c2 |
Assignments
| Operation | Effect |
| c1=c2 | Assigns all elements of c2 to c1 |
| c.assign(b,elem) | Assigns n copies of element elem |
| c.assign(begin,end) | Assigns the elements of the range [begin, end] |
| c1.swap(c2) | Swaps the data of c1 and c2 |
| swap(c1,c2) | Same (as global function) |
Element Access
| Operation | Effect |
| c.at(i) | Returns the element with index i (throws range error exception if i is out of range) |
| c[i] | Returns the element with index i (without range checking) |
| c.front() | Returns the first element (no check if there is a first element) |
| c.back() | Returns the last element (no check if there is a last element) |
Iterator Functions
| Operation | Effect |
| c.begin() | Returns a random access iterator for the first element |
| c.end() | Returns a random access iterator for the position after the last element |
| c.rbegin() | Returns a reverse iterator for the first element of a reverse iteration |
| c.rend() | Returns a reverse iterator for the position after the last element of a reverse iteration |
Inserting and Removing Elements
| Operation | Effect |
| c.insert(pos,El) | Inserts at iterator position pos a copy of El and returns the position of the new element |
| c.insert(pos,nrEl,El) | Inserts at iterator position pos, nrEl copies of El (returns nothing) |
| c.insert(pos,beg,end) | Inserts at iterator position pos a copy of all elements of the range [beg,end) (returns nothing) |
| c.push_back(El) | Appends a copy of El at the end |
| c.pop_back() | Removes the last element (does not return it) |
| c.erase(pos) | Removes the element at iterator position pos and returns the position of the next element |
| c.erase(beg,end) | Removes all elements of the range [beg,end) and returns the position of the next element |
| c.resize(n) | Changes the number of elements to n (if size() grows new elements are created by their default constructor) |
| c.resize(n,El) | Changes the number of elements to n (if size() grows new elements are copies of El |
| c.clear() | Removes all elements |
References
Example 1
ProblemThe following program creates an empty vector of type int and then makes some operation using the vector.
Workings#include<iostream>
#include<vector>
using namespace std;
typedef vector<int> INTVECTOR;
const SIZE=4;
void main(void)
{
//dynamically allocated vector initially contains no elements
INTVECTOR Vect;
for (int i=0;i<SIZE;i++)
Vect.push_back((i+1)*100);
//initializes the vector with [100, 200, 300, 400]
cout <<"First element is "<<Vect.front()<<"."<<endl;
cout <<"Last element is "<<Vect.back()<<"."<<endl;
cout <<"The vector contains "<<Vect.size()<<" elements."<<endl;
cout <<"Erase the last element."<<endl;
Vect.erase(Vect.end()-1); //erase the last element in the vector
cout <<"The new last element is "<<Vect.back()<<"."<<endl;
cout <<"Erase the first element."<<endl;
Vect.erase(Vect.begin()); // erase the first element in the vector
cout <<"The new first element is "<<Vect.front()<<"."<<endl;
cout <<"The vector contains "<<Vect.size()<<"elements."<<endl;
}
SolutionOutput:
First element is 100.
Last element is 400.
The vector contains 4 elements.
Erase the last element.
The new last element is 300.
Erase the first element.
The new first element is 200.
The vector contains 2 elements.
Example 2
ProblemThis particular program creates 2 vector objects, one an int specialization and one a string specilization;each has 5 elements.
Workings#include<iostream>
#include<string>
#include<vector>
const int N=5;
int main()
{
using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;
vector<int> ratings(N);
vector<string> titles(N);
cout <<"You will enter \n"<<N<<"book titles and your ratings (0-10). \n";
for(int i=0;i<N;i++)
{
cout <<"Title "<<i+1<<":";
getline(cin,titles[i]);
cout <<"Rating (0-10):";
cin >>ratings[i];
cin.get();
}
cout <<"You entered the following: \n"<<"Rating\tBook\n";
for(i=0;i<N;i++)
{
cout <<ratings[i]<<"\t"<<titles[i]<<endl;
}
return 0;
}
SolutionOutput:
You will enter 5 book titles and your ratings (0-10).
Title 1: T1
Rating (0-10): 7
Title 2: T2
Rating (0-10): 5
Title 3: T3
Rating (0-10): 4
Title 4: T4
Rating (0-10): 9
Title 5: T5
Rating (0-10): 3
You entered the following:
Rating Book
7 Title 1
5 Title 2
4 Title 3
9 Title 4
3 Title 5
Example 3
ProblemThis example shows 3 methods of accessing the data using a vector.
Workings#include<iostream>
#include<vector>
#include<string>
using namespace std;
main()
{
vector<string> S;
S.push_back("The number is 100.");
S.push_back("The number is 200.");
S.push_back("The number is 300.");
cout <<"Loop by index: "<<endl;
int i;
for(i=0;i<S.size();i++)
{
cout <<S[i]<<endl;
}
cout <<endl<<"Constant Iterators"<<endl;
vector<string>::const_iterator c_i;
for(c_i=S.begin();c_i!=S.end();c_i++)
{
cout <<*c_i<<endl;
}
cout <<endl<<"Reverse Iterator"<<endl;
vector<string>::reverse_iterator r_i;
for(r_i=S.rbegin();r_i!=S.rend();++r_i)
{
cout <<*r_i<<endl;
}
cout <<endl<<"Sample Output"<<endl;
cout <<S.size()<<endl;
cout <<S[2]<<endl;
swap(S[0],S[2]);
cout <<S[2]<<endl;
}
SolutionOutput:
Loop by index:
The number is 100.
The number is 200.
The number is 300.
Constant Iterator:
The number is 100.
The number is 200.
The number is 300.
Reverse Iterator:
The number is 300.
The number is 200.
The number is 100.
Sample Output:
3
The number is 300.
The number is 100.
Example 4
ProblemExample of iterators used with a two dimensional vector.
Workings#include<iostream>
#include<vector>
using namespace std;
main()
{
vector< vector<int> > vMat; // declare two dimensional vector
vector<int> X,Y;
vector< vector<int> >::iterator iter_i;
vector<int>::iterator iter_j;
X.push_back(100);
X.push_back(200);
X.push_back(300);
Y.push_back(10);
Y.push_back(20);
Y.push_back(30);
vMat.push_back(X);
vMat.push_back(Y);
cout << endl << "Using Iterator:" << endl;
for(iter_i=vMat.begin(); iter_i!=vMat.end(); iter_i++)
{
for(iter_j=(*iter_i).begin(); iter_j!=(*iter_i).end(); iter_j++)
{
cout << *iter_j << endl;
}
}
}
SolutionOutput:
Using Iterator:
100
200
300
10
20
30
NOTE! "end()" points to a position after the last element and thus can NOT be used to point to the last element.
Example 5
ProblemThis program illustrates reverse iterators of the vector class, as well as member functions rbegin() and rend().
Workings#include <iostream>
#include <vector>
using namespace std;
int main()
{
cout <<"\nHere are the contents of a vector of size 12:\n";
int a[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24};
vector<int> v(a, a+12);
vector<int>::iterator p = v.begin();
while (p != v.end())
cout <<*p++<<" ";
cout <<"\nNow using a reverse iterator to display\n"
"the vector components in reverse order:\n";
vector<int>::reverse_iterator r_p = v.rbegin();
while (r_p != v.rend())
cout << *r_p++ << " ";
cout <<"\nNow using a reverse iterator to display\n"
"the vector components in forward order:\n";
r_p = v.rend();
while (r_p != v.rbegin())
cout <<*--r_p<<" ";
cout <<"\nNow constructing a new vector containing the "
"values from 18 down to 6 from\nthe first vector, and "
"then displaying the values from this new vector.\n";
vector<int> v1(v.rbegin()+3, v.rbegin()+10);
p = v1.begin();
while (p != v1.end())
cout <<*p++<<" ";
return 0;
}
SolutionOutput:
Here are the contents of a vector of size 12:
2 4 6 8 10 12 14 16 18 20 22 24
Now using a reverse iterator to display
the vector components in reverse order:
24 22 20 18 16 14 12 10 8 6 4 2
Now using a reverse iterator to display
the vector components in forward order:
2 4 6 8 10 12 14 16 18 20 22 24
Now constructing a new vector containing the values from 18 down to 6 from
the first vector, and then displaying the values from this new vector.
18 16 14 12 10 8 6
References