Arrays and Vectors: 2006 Pearson Education, Inc. All Rights Reserved
Arrays and Vectors: 2006 Pearson Education, Inc. All Rights Reserved
7.1 Introduction
7.2 Arrays
7.3 Declaring Arrays
7.4 Examples Using Arrays
7.5 Passing Arrays to Functions
7.6 Case Study: Class GradeBook Using an Array to Store Grades
7.7 Searching Arrays with Linear Search
7.8 Sorting Arrays with Insertion Sort
7.9 Multidimensional Arrays
7.10 Case Study: Class GradeBook Using a Two-Dimensional Array
7.11 Introduction to C++ Standard Library Class Template vector
7.12 (Optional) Software Engineering Case Study: Collaboration
Among Objects in the ATM System
7.13 Wrap-Up
7.1 Introduction
• Arrays
– Data structures containing related data items of same type
– Always remain the same size once created
• Are “static” entities
– Character arrays can also represent strings
– C-style pointer-based arrays vs. vectors (object-based)
• Vectors are safer and more versatile
7.2 Arrays
• Array
– Consecutive group of memory locations
• All of which have the same type
– Index
• Position number used to refer to a specific location/element
• Also called subscript
• Place in square brackets
– Must be positive integer or integer expression
• First element has index zero
• Example (assume a = 5 and b = 6)
– c[ a + b ] += 2;
• Adds 2 to array element c[ 11 ]
Grade distribution:
0-9:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
100: *
Face Frequency
1 1000167
2 1000149
3 1000152
4 998748
5 999626
6 1001158
82 int GradeBook::getMaximum()
Student 1: 87
Student 2: 68 fig07_18.cpp
Student 3: 94
Student 4: 100
Student 5: 83 (2 of 2)
Student 6: 78
Student 7: 85
Student 8: 91
Student 9: 76
Student 10: 87
Grade distribution:
0-9:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
100: *
• Sorting data
– One of the most important computing applications
• Virtually every organization must sort some data
• Insertion sort
– Simple but inefficient
– First iteration takes second element
• If it is less than the first element, swap it with first element
– Second iteration looks at the third element
• Insert it into the correct position with respect to first two
elements
– …
– At the ith iteration of this algorithm, the first i elements in
the original array will be sorted
Unsorted array:
34 56 4 10 77 51 93 30 5 52
Sorted array:
4 5 10 30 34 51 52 56 77 93
integers1[5] is 13