A vector is a collection of objects, all of which have the same type. Every object in the collection has an associated index, which gives access to that object. A vector is often referred to as a container because it “contains” other objects. We’ll have much more to say about containers in Part II.
To use a vector, we must include the appropriate header. In our examples, we also assume that an appropriate using declaration is made:
- #include <vector>
- using std::vector;
A vector is a class template. C++(www.cppentry.com) has both class and function templates. Writing a template requires a fairly deep understanding of C++(www.cppentry.com). Indeed, we won’t see how to create our own templates until Chapter 16! Fortunately, we can use templates without knowing how to write them.
Templates are not themselves functions or classes. Instead, they can be thought of as instructions to the compiler for generating classes or functions. The process that the compiler uses to create classes or functions from templates is called instantiation. When we use a template, we specify what kind of class or function we want the compiler to instantiate.
For a class template, we specify which class to instantiate by supplying additional information, the nature of which depends on the template. How we specify the information is always the same: We supply it inside a pair of angle brackets following the template’s name.
In the case of vector, the additional information we supply is the type of the objects the vector will hold:
- vector<int> ivec;
- vector<Sales_item> Sales_vec;
- vector<vector<string>> file;
In this example, the compiler generates three distinct types from the vector template: vector<int>, vector<Sales_item>, andvector<vector<string>>.
vector is a template, not a type. Types generated from vector must include the element type, for example, vector<int>.
We can define vectors to hold objects ofmost any type. Because references are not objects (§ 2.3.1, p. 50), we cannot have a vector of references. However, we can have vectors ofmost other (nonreference) built-in types andmost class types. In particular, we can have vectors whose elements are themselves vectors.
It is worth noting that earlier versions of C++(www.cppentry.com) used a slightly different syntax to define a vector whose elements are themselves vectors (or another template type). In the past, we had to supply a space between the closing angle bracket of the outer vector and its element type—vector<vector<int> > rather than vector<vector<int>>.
Some compilers may require the old-style declarations for a vector of vectors, for example, vector<vector<int> >.