3.3.1 Defining and Initializing vectors
As with any class type, the vector template controls how we define and initialize vectors. Table 3.4 (p. 99) lists the most common ways to define vectors.
We can default initialize a vector (§ 2.2.1, p. 44), which creates an empty vector of the specified type:
- vector<string> svec;
It might seem that an empty vector would be of little use. However, as we’ll see shortly, we can (efficiently) add elements to a vector at run time. Indeed, the most common way of using vectors is to define an initially empty vector to which elements are added as their values become known at run time. We can also supply initial value(s) for the element(s)when we define a vector. For example, we can copy elements from another vector. When we copy a vector, each element in the new vector is a copy of the corresponding element in the original vector. The two vectors must be the same type:
- vector<int> ivec;
-
- vector<int> ivec2(ivec);
- vector<int> ivec3 = ivec;
- vector<string> svec(ivec2);