Vector operations, Declaration and initialization of vectors – HP Integrity NonStop H-Series User Manual

Page 56

Advertising
background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

Vector Operations

Each of the member functions provided by the vector data type will shortly be described in more
detail. Note that while member functions provide basic operations, the utility of the data structure is
greatly extended through the use of the generic algorithms described in Chapters

13

and

14

.

Declaration and Initialization of Vectors

Requirements of an Element Type

Because it is a template class, the declaration of a vector must include a designation of the
component type. This can be a primitive language type (such as integer or double), a pointer type,
or a user-defined type. In the latter case, the user-defined type must implement a default constructor,
as this constructor is used to initialize newly created elements. A copy constructor, either explicitly
or implicitly defined, must also exist for the container element type. Like an array, a vector is most
commonly declared with an integer argument that describes the number of elements the vector will
hold:

vector<int> vec_one(10);

The constructor used to create the vector in this situation is declared as explicit, which prevents it
being used as a conversion operator. (This is generally a good idea, since otherwise an integer might
unintentionally be converted into a vector in certain situations.)

There are a variety of other forms of constructor that can also be used to create vectors. In addition
to a size, the constructor can provide a constant value that will be used to initialize each new vector
location. If no size is provided, the vector initially contains no elements, and increases in size
automatically as elements are added. The copy constructor creates a clone of a vector from another
vector.

vector<int> vec_two(5, 3); // copy constructor
vector<int> vec_three;
vector<int> vec_four(vec_two); // initialization by assignment

A vector can also be initialized using elements from another collection, by means of a beginning
and ending iterator pair. The arguments can be any form of iterator; thus collections can be
initialized with values drawn from any of the container classes in the standard library that support
iterators.

vector <int> vec_five (aList.begin(), aList.end());

Advertising
This manual is related to the following products: