apvector
class
Built-in arrays
There is a class Vector
defined as part of the STL library in the C++ standard. The class Vector
declared in vector.h
is consistent with this standard class. There is also apvector
, defined for use in the Advanced Placement computer science course. The apvector
class is based on the class Vector
, and all member function of the apvector
class are also member functions of the Vector
class
The apvector
class is a template class in that you may specify the type of information that the homogeneous collection will hold.
apvectors
, like arrays, are indexed beginning at zero.
apvectors
can be initialized to hold the same value in every cell by providing a second argument to the constructor when the vector is defined.
apvectors
can be resized.
apvectors
should always be passed by reference to save memory and the time that would be required to copy if pass by value were used. There are occasions when a copy is needed, but in general pass by reference is preferred. Use const
reference parameters to protect the parameter from being altered even when passed by reference.
APCS - the apvector
class
Arrays are ordered collections of homogeneous elements. In this course
we will use the apvector
class to implement resizable
one-dimensional arrays. Elements of apvectors
are
initialized beginning at zero and are accessed in the same way as
built-in C++ arrays. But unlike built-in arrays, this class checks
subscripts at runtime to ensure that they fall within the legal range.
This eliminates subscript out-of-bounds bugs that often crash the
system. In addition, the length of an apvector
is stored
within the vector, eliminating the need for an extra variable.
One apvector
can be copied to another with the overloaded
assignment operator. When a local apvector
is declared,
the compiler only needs to allocate stack space for its length and a
pointer to the actual array because the actual array is allocated
dynamically from the much larger free store memory.
Here are examples of the four apvector constructors -
|
#include "apvector.h" // include the header file; tell the compiler where it is n = counters.length( ); // determine the current length of the array counters.resize(2*n); // double the size of the array counters[0] = 42; // store 42 in the first element of the array // These prototype functions show how to always pass array objects by reference. void fillArray(apvector<int> &counters); // Note that the & must be explicitly used when an array object is passed by reference. void displayArray(const apvector<int> &counters); // To avoid unnecessary copying, do not pass an array object by value . // Pass by reference using the keyword const to ensure the array cannot be changed.