7.1. Introduction
This chapter introduces the important topic of data structures—collections of related data
items. Arrays are
data structures consisting of related data items of the same type. We considered
classes in Chapter
3. In Chapter
19, Bits, Characters, C Strings and structs, we discuss the notion
of structures.
Structures and classes can each hold related data items of possibly different
types. Arrays, structures and classes are "static" entities in that they remain
the same size throughout program execution. (They may, of course, be of
automatic storage class and hence be created and destroyed each time the blocks
in which they are defined are entered and exited.)
After discussing how arrays are
declared, created and initialized, we present a series of practical examples
that demonstrate several common array manipulations. We then explain how
character strings (represented until now by string objects) can also be represented by character arrays.
We present an example of searching arrays to find particular elements. The
chapter also introduces one of the most important computing applications—sorting
data (i.e., putting the data in some particular order). Two sections of the
chapter enhance the case study of class GradeBook in Chapters
3–6. In particular, we use arrays to enable the class to
maintain a set of grades in memory and analyze student grades from multiple exams in a semester—two capabilities that were
absent from previous versions of the GradeBook class. These and other chapter examples demonstrate
the ways in which arrays allow programmers to organize and manipulate data.
The style of arrays we use throughout
most of this chapter are C-style pointer-based arrays. (We'll study pointers in
Chapter
8.) In the final section of this chapter, and in Chapter
20, Standard Template Library (STL), we'll cover
arrays as full-fledged objects called vectors. We'll discover that these
object-based arrays are safer and more versatile than the C-style, pointer-based
arrays we discuss in the early part of this chapter.