Sams Teach Yourself C++ in 21 Days

(singke) #1
On line 90, a vector of three Studentobjects is defined. Its size and capacity are both
three. Elements in the GrowingClassare assigned with the Studentobjects on lines
94–96 using the subscripting operator [].
The fourth student,Peter, is added to the vector on line 100. This increases the size of
the vector to four. Interestingly, its capacity is now set to six. This means that the com-
piler has allocated enough space for up to six Studentobjects.
Because vectors must be allocated to a continuous block of memory, expanding them
requires a set of operations. First, a new block of memory large enough for all four
Studentobjects is allocated. Second, the three elements are copied to this newly allo-
cated memory and the fourth element is appended after the third element. Finally, the
original memory block is returned to the memory. When a large number of elements are
in a vector, this deallocation and reallocation process can be time-consuming. Therefore,
the compiler employs an optimization strategy to reduce the possibility of such expensive
operations. In this example, if you append one or two more objects to the vector, no need
exists to deallocate and reallocate memory.
On lines 104 and 105, the subscripting operator []is again used to change the member
variables for the first object in the GrowingClass.

700 Day 19


DOdefine a default constructor for a
class if its instances are likely to be held
in a vector.
DOdefine a copy constructor for such a
class.
DOdefine an overloaded assignment
operator for such a class.

DON’T create your own vector class! You
can use the one in the STL. Because this
is a part of the C++ standard, any stan-
dard compliant compiler should have this
class!

DO DON’T


The vectorcontainer class has other member functions. The front()function returns a
reference to the first element in a list. The back()function returns a reference to the last
element. The at()function works like the subscript operator []. It is safer than the vec-
tor implementation of []because it checks whether the subscript passed to it is within
the range of available elements (although, of course, you could code a subscript operator
to perform the same check). If the index is out of range, it throws an out_of_range
exception. (Exceptions are covered tomorrow.)
Theinsert()function inserts one or more nodes into a given position in a vector. The
pop_back()function removes the last element from a vector. And finally, a remove()
function removes one or more elements from a vector.
Free download pdf