Vector Type
A vector is a collection of objects of a single type, each of which has an associated integer index. As with strings, the library takes care of managing the memory associated with storing the elements. We speak of a vector as a container because it contains other objects. All of the objects in a container must have the same type.
To use a vector, we must include the appropriate header. In our examples, we also assume an appropriate using declaration is made.
Cosnider the following example for vectors working :
Example
// constructing vectors #include <iostream> #include <vector> using namespace std; int main() { unsigned int i; // constructors used in the same order as described above: vector<int> first; // empty vector of ints vector<int> second(4, 100); // four ints with value 100 vector<int> third(second.begin(), second.end()); // iterating through second vector<int> fourth(third); // a copy of third // the iterator constructor can also be used to construct from arrays: int myints[] = { 16, 2, 77, 29 }; vector<int> fifth(myints, myints + sizeof(myints) / sizeof(int)); cout << "The contents of fifth are:"; for (vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it) cout << ' ' << *it; cout << '\n'; getchar(); return 0; }
Output
The contents of fifth are: 16 2 77 29