An array
is a collection of storage locations for a specific type of data. Think of an array
as a "box"
drawn in memory with a series of subdivisions, called elements, to store data.
The box below could represent an array of 10 integers.
While this array contains only 10 elements, arrays are traditionally used to handle large amounts of data.
It is important to remember that all of the elements in an array must contain the same
type of data.
FYI only:
In Standard C++, arrays can be handled in the following manner:
integer printerModel[4];
// array of four elements of type integer
Arrays can be initialized by
placing a list of values, separated by commas, within
braces.
double printerModel[4]
= {550, 580, 850, 880};
Individual elements of an array are accessed using subscripts (or
indices) such as printerModel[0],
printerModel[1], printerModel[2], and printerModel[3].
(Note the subscripts from
0 to 3.)
Unfortunately, the Standard C++ compiler
does not keep track of the size of a declared array. It also, will
not tell you if your subscript value should go out of range and not
actually point to an element within the array. |
The College Board has developed a way for us to deal with these shortcomings
of Standard C++ when dealing with arrays. We will be using the
apvector
class.
The apvector class is an improvement over Standard C++
array manipulation in that it will:
1. check the subscript values and warn the
programmer of illegal
subscripts (should your subscripts go out of range).
2. keep track of the size of an array. It also offers the function
length()
that will return the size of an array.
3. allow an array to be resized.
Syntax:
apvector <int> grades(5);
creates an array of 5 integer elements
which are named:
grades[0]
grades[1]
grades[2]
grades[3]
grades[4]
Did you notice the zero subscript in the
first element?
|