vector
Template ClassThe vector
template class is similar to the string
class in that it is a dynamic array. You can set the size of a vector
object during runtime, and you can append new data to the end or insert new data in the middle. Basically, it’s an alternative to using new
to create a dynamic array. Actually, the vector
class does use new
and delete
to manage memory, but it does so automatically.
At this time we won’t venture very deeply into what it means to be a template class. Instead, we’ll look at a few basic practical matters. First, to use a vector
object, you need to include the vector
header file. Second, the vector
identifier is part of the std
namespace, so you can use a using
directive, a using
declaration, or std::vector
. Third, templates use a different syntax to indicate the type of data stored. Fourth, the vector
class uses a different syntax to indicate the number of elements. Here are some examples:
#include <vector>
...
using namespace std;
vector<int> vi; // create a zero-size array of int
int n;
cin >> n;
vector<double> vd(n); // create an array of n doubles
We say that vi
is an object of type vector<int>
and that vd
is an object of type vector<double>
. Because vector
objects resize automatically when you insert or add values to them, it’s okay for vi
to start with 0 size. But for the resizing to work, you would use the various methods that are part of the vector
package.
In general, the following declaration creates a vector
object vt
that can hold n_elem
elements of type typeName
:
vector<typeName> vt(n_elem);
The parameter n_elem
can be an integer constant or an integer variable.
18.189.171.153