Managing Arrays and Strings 445
13
- Bag—An unordered collection that is added to and retrieved in indeterminate
order.
By overloading the index operator ([ ]), you can turn a linked list into an ordered col-
lection. By excluding duplicates, you can turn a collection into a set. If each object in the
list has a pair of matched values, you can use a linked list to build a dictionary or a
sparse array.
Writing your own array class has many advantages over using the built-in
arrays. Using the Standard Library implementations of similar classes usually
has advantages over writing your own classes.
NOTE
Summary ..............................................................................................................
Today, you learned how to create arrays in C++. An array is a fixed-size collection of
objects that are all the same type.
Arrays don’t do bounds checking. Therefore, it is legal—even if disastrous—to read or
write past the end of an array. Arrays count from 0. A common mistake is to write to off-
set nof an array of nmembers.
Arrays can be one dimensional or multidimensional. In either case, the members of the
array can be initialized, as long as the array contains either built-in types, such as int,or
objects of a class that has a default constructor.
Arrays and their contents can be on the free store or on the stack. If you delete an array
on the free store, remember to use the brackets in the call to delete.
Array names are constant pointers to the first elements of the array. Pointers and arrays
use pointer arithmetic to find the next element of an array.
Strings are arrays of characters, or chars. C++ provides special features for managing
chararrays, including the capability to initialize them with quoted strings.
Q&A ....................................................................................................................
Q What is in an uninitialized array element?
A Whatever happens to be in memory at a given time. The results of using an unini-
tialized array member without assigning a value can be unpredictable. If the com-
piler is following the C++ standards, array elements that are static, nonlocal objects
will be zero initialized.