How to Use the Vector STL Container Class
A container class is a class whose instances contain other classes. The Standard Template Library (STL) for C++ is available on the STL home webpage and consists of associative containers, sequences, strings and more. The vector class is a sequence and like all of the container classes, it is a template that may contain any object type. The following steps explain how to use this vector STL container class.
Instructions
-
-
1
Study what the vector class does. It supports insertion and deletion of its elements and random access to those elements. A vector's memory is managed automatically managed and its elements may vary dynamically.
-
2
Know where vector is defined. It is in a standard header called vector and a nonstandard header called vector.h which is included for backward-compatibility.
-
-
3
Learn the syntax for the vector class. It is Vector
where T is the type of object to be stored in the vector and Alloc is number of elements to allocate memory. -
4
Look at the following example for a simple use of the vector class:
//declare the vector
vectortest(3);
v[0] = 5;
v[1] = v[0] + 2;
//v[2] = 5 + 2 = 7
v[2] = v[0] +v[1];
// v[0] = 7, v[1] = 2, v[2] = 5
reverse(v.begin(),v.end());Note vector
is used the same as an ordinary array without having to allocate memory. -
5
Observe the use of reverse in the last line of the code in Step 4. This function takes a range of elements (the entire vector v in this case) and reverses their order.
-
1