chap09 - Arrays and Vectors Mechanism for representing lists Lists Problem solving often requires information be viewed as a list List may be

chap09 - Arrays and Vectors Mechanism for representing...

This preview shows page 1 - 14 out of 84 pages.

Arrays and Vectors Mechanism for representing lists
Image of page 1
Lists Problem solving often requires information be viewed as a list List may be one-dimensional or multidimensional C++ provides two list mechanisms Arrays Traditional and important because of legacy libraries Restrictions on its use Container classes First-class list representation Common containers provided by STL Vector, queue, stack, map, … Preferred long-term programming practice
Image of page 2
Lists Analogies Egg carton Apartments Cassette carrier
Image of page 3
Array Terminology List is composed of elements Elements in a list have a common name The list as a whole is referenced through the common name List elements are of the same type the base type Elements of a list are referenced by subscripting or indexing the common name
Image of page 4
C++ Restrictions Subscripts are denoted as expressions within brackets: [ ] Base type can be any fundamental, library -defined, or programmer-defined type The index type is integer and the index range must be 0 ... n -1 where n is a programmer-defined constant expression. Parameter passing style Always call by reference (no indication necessary)
Image of page 5
Basic Array Definition Type of values in list BaseType Id [ SizeExp ] ; Name of list Bracketed constant expression indicating number of elements in list double X [ 100 ] ; // Subscripts are 0 through 99
Image of page 6
Example Definitions Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000; Then the following are all correct array definitions int A[10]; // array of 10 ints char B[MaxStringSize]; // array of 80 chars double C[M*N]; // array of 800 floats int Values[MaxListSize]; // array of 1000 ints Rational D[N-15]; // array of 5 Rationals
Image of page 7