Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1
Starting Out with C++, 3rd Edition
7.1 Arrays Hold Multiple values
2
Starting Out with C++, 3rd Edition
Figure 7-1
3
Starting Out with C++, 3rd Edition
Figure 7-2
4
Starting Out with C++, 3rd Edition
Table 7-1
5
Starting Out with C++, 3rd Edition
7.2 Accessing Array elements
6
Starting Out with C++, 3rd Edition
Program 7-1
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element int array to store the
// values.
#include <iostream.h>
void main(void)
{
short hours[6];
7
Starting Out with C++, 3rd Edition
Program continues
cin >> hours[4];
cin >> hours[5];
cout << "The hours you entered are:";
cout << " " << hours[0];
cout << " " << hours[1];
cout << " " << hours[2];
cout << " " << hours[3];
cout << " " << hours[4];
cout << " " << hours[5] << endl;
}
8
Starting Out with C++, 3rd Edition
Program Output with Example Input
9
Starting Out with C++, 3rd Edition
Figure 7-7
10
Starting Out with C++, 3rd Edition
Program 7-2
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element short array to store the
// values.
#include <iostream.h>
void main(void)
{
short hours[6];
11
Starting Out with C++, 3rd Edition
Program Output with Example Input
12
Starting Out with C++, 3rd Edition
Program 7-3
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element short array to store the
// values.
#include<iostream.h>
void main(void)
{
short hours[6];
13
Starting Out with C++, 3rd Edition
Program continues
14
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter the hours worked by six employees.
Employee 1: 20 [Enter]
Employee 2: 12 [Enter]
Employee 3: 40 [Enter]
Employee 4: 30 [Enter]
Employee 5: 30 [Enter]
Employee 6: 15 [Enter]
The hours you entered are
Employee 1: 20
Employee 2: 12
Employee 3: 40
Employee 4: 30
Employee 5: 30
Employee 6: 15
15
Starting Out with C++, 3rd Edition
7.3 No Bounds Checking in C++
16
Starting Out with C++, 3rd Edition
Program 7-4
// This program unsafely accesses an area of memory by writing
// values beyond an array's boundary.
// WARNING: If you compile and run this program, it could cause
// the computer to crash.
#include <iostream.h>
void main(void)
{
short values[3]; // An array of 3 short integers.
17
Starting Out with C++, 3rd Edition
Figure 7-8
18
Starting Out with C++, 3rd Edition
7.4 Array Initialization
19
Starting Out with C++, 3rd Edition
Program 7-5
// This program displays the number of days in each month.
// It uses a 12-element int array.
#include <iostream.h>
void main(void)
{
int days[12];
days[0] = 31; // January
days[1] = 28; // February
days[2] = 31; // March
days[3] = 30; // April
days[4] = 31; // May
days[5] = 30; // June
days[6] = 31; // July
20
Starting Out with C++, 3rd Edition
Program continues
21
Starting Out with C++, 3rd Edition
Program Output
22
Starting Out with C++, 3rd Edition
Program 7-6
// This program displays the number of days in each month.
// It uses a 12-element int array.
#include <iostream.h>
void main(void)
{
int days[12] = {31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31};
for (int count = 0; count < 12; count++)
{
cout << "Month " << (count + 1) << " has ";
cout << days[count] << " days.\n";
}
}
23
Starting Out with C++, 3rd Edition
Program Output
24
Starting Out with C++, 3rd Edition
Program 7-7
// This program uses an array of ten characters to store the
// first ten letters of the alphabet. The ASCII codes of the
// characters are displayed.
#include <iostream.h>
void main(void)
{
char letters[10] = {'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J'};
25
Starting Out with C++, 3rd Edition
Program Output
26
Starting Out with C++, 3rd Edition
Partial Array Initialization
27
Starting Out with C++, 3rd Edition
Program 7-8
// This program has a partially initialized array.
#include <iostream.h>
void main(void)
{
int numbers[7] = {1, 2, 4, 8}; // Initialize the
// first 4 elements.
28
Starting Out with C++, 3rd Edition
Program Output
29
Starting Out with C++, 3rd Edition
Implicit Array Sizing
30
Starting Out with C++, 3rd Edition
Initializing With Strings
31
Starting Out with C++, 3rd Edition
Figure 7-11
32
Starting Out with C++, 3rd Edition
Program 7-9
// This program displays the contents of two char arrays.
#include <iostream.h>
void main(void)
{
char name1[] = "Holly";
char name2[] = {'W', 'a', 'r', 'r', 'e', 'n', '\0'};
33
Starting Out with C++, 3rd Edition
Program Output
Holly
Warren
34
Starting Out with C++, 3rd Edition
7.5 Processing Array Contents
35
Starting Out with C++, 3rd Edition
Program 7-10
// This program stores, in an array, the hours worked by 5
// employees who all make the same hourly wage.
#include <iostream.h>
void main(void)
{
int hours[5];
float payRate;
36
Starting Out with C++, 3rd Edition
Program continues
cout << "Enter the hourly pay rate for all the employees: ";
cin >> payRate;
cout << "Here is the gross pay for each employee:\n";
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
for (index = 0; index < 5; index++)
{
float grossPay = hours[index] * payRate;
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
}
37
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter the hours worked by 5 employees who all
earn the same hourly rate.
Employee #1: 5 [Enter]
Employee #2: 10 [Enter]
Employee #3: 15 [Enter]
Employee #4: 20 [Enter]
Employee #5: 40 [Enter]
Enter the hourly pay rate for all the employees: 12.75 [Enter]
Here is the gross pay for each employee:
Employee #1: $63.75
Employee #2: $127.50
Employee #3: $191.25
Employee #4: $255.00
Employee #5: $510.00
38
Starting Out with C++, 3rd Edition
Program 7-11
// This program stores, in an array, the hours worked by 5
// employees who all make the same hourly wage. It then
// displays the gross pay, including any overtime.
#include <iostream.h>
void main(void)
{
int hours[5];
float payRate;
39
Starting Out with C++, 3rd Edition
Program continues
cout << "Enter the hourly pay rate for all the employees: ";
cin >> payRate;
cout << "Here is the gross pay for each employee:\n";
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
for (index = 0; index < 5; index++)
{
float grossPay, overTime;
if (hours[index] > 40)
{
// Calculate pay for 40 hours.
grossPay = 40 * payRate;
// Calculate overtime pay.
overTime = (hours[index] - 40) * 1.5 * payRate;
// Add regular pay and overtime pay.
grossPay += overTime;
}
40
Starting Out with C++, 3rd Edition
Program continues
else
grossPay = hours[index] * payRate;
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
}
41
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter the hours worked by 5 employees who all
earn the same hourly rate.
Employee #1: 10 [Enter]
Employee #2: 20 [Enter]
Employee #3: 50 [Enter]
Employee #4: 40 [Enter]
Employee #5: 60 [Enter]
Enter the hourly pay rate for all the employees: 12.75 [Enter]
Here is the gross pay for each employee:
Employee #1: $127.50
Employee #2: $255.00
Employee #3: $701.25
Employee #4: $510.00
Employee #5: $892.50
42
Starting Out with C++, 3rd Edition
7.6 Focus on Software Engineering:
Parallel Arrays
• By using he same subscript, you can build
relationships between data stored in two or
more arrays.
43
Starting Out with C++, 3rd Edition
Program 7-12
// This program stores, in two arrays, the hours worked by 5
// employees, and their hourly pay rates.
#include <iostream.h>
void main(void)
{
int hours[numEmps];
float payRate[numEmps];
44
Starting Out with C++, 3rd Edition
Program continues
cin >> hours[index];
cout << "Hourly pay rate for employee #";
cout << (index + 1) << ": ";
cin >> payRate[index];
}
cout << "Here is the gross pay for each employee:\n";
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
for (index = 0; index < numEmps; index++)
{
float grossPay = hours[index] * payRate[index];
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
}
45
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter the hours worked by 5 employees and their hourly rates.
hours worked by employee #1: 10 [Enter]
Hourly pay rate for employee #1: 9.75 [Enter]
hours worked by employee #2: 15 [Enter]
Hourly pay rate for employee #2: 8.62 [Enter]
hours worked by employee #3: 20 [Enter]
Hourly pay rate for employee #3: 10.50 [Enter]
hours worked by employee #4: 40 [Enter]
Hourly pay rate for employee #4: 18.75 [Enter]
hours worked by employee #5: 40 [Enter]
Hourly pay rate for employee #5: 15.65 [Enter]
46
Starting Out with C++, 3rd Edition
7.7 Thou Shalt Not Assign
47
Starting Out with C++, 3rd Edition
Table 7-2
Expression Value
48
Starting Out with C++, 3rd Edition
7.8 Printing the Contents of an
Array
• To display the contents of an array, you
must use a loop to display the contents of
each element.
int array[5] = { 10, 20, 30, 40, 50 };
for (int count = 0; count < 5; count++)
cout << array[count] << endl;
49
Starting Out with C++, 3rd Edition
7.9 Arrays As Function Arguments
50
Starting Out with C++, 3rd Edition
Program 7-13
// This program demonstrates that an array element is passed
// to a function like any other variable.
#include <iostream.h>
void main(void)
{
int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};
51
Starting Out with C++, 3rd Edition
Program continues
//************************************
// Definition of function showValue. *
// This function accepts an integer argument. *
// The value of the argument is displayed. *
//************************************
void ShowValue(int Num)
{
cout << Num << " ";
}
52
Starting Out with C++, 3rd Edition
Program Output
5 10 15 20 25 30 35 40
53
Starting Out with C++, 3rd Edition
Program 7-14
// This program demonstrates an array being passed to a function.
#include <iostream.h>
void main(void)
{
int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};
//***********************************************
// Definition of function showValues. *
// This function accepts an array of 8 integers *
// as its argument. The contents of the array *
// is displayed. *
//***********************************************
void showValues(int nums[])
{
for (int index = 0; index < 8; index++)
cout << nums[index] << " ";
}
54
Starting Out with C++, 3rd Edition
Program Output
5 10 15 20 25 30 35 40
55
Starting Out with C++, 3rd Edition
Program 7-15
// This program demonstrates an array being passed to a function.
#include <iostream.h>
void main(void)
{
int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int set2[8] = {2, 4, 6, 8, 10, 12, 14, 16};
showValues(set1);
cout << endl;
showValues(set2);
}
//***********************************************
// Definition of function showValues. *
// This function accepts an array of 8 integers *
// as its argument. The contents of the array *
// is displayed. *
//***********************************************
void showValues(int nums[])
{
for (int index = 0; index < 8; index++)
cout << nums[index] << " ";
}
56
Starting Out with C++, 3rd Edition
Program Output
5 10 15 20 25 30 35 40
2 4 6 8 10 12 14 16
57
Starting Out with C++, 3rd Edition
Program 7-16
// This program uses a function that can display the contents
// of an integer array of any size.
#include <iostream.h>
void main(void)
{
int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int set2[4] = {2, 4, 6, 8};
int set3[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
showValues(set1, 8);
cout << endl;
showValues(set2, 4);
cout << endl;
showValues(set3, 12);
}
58
Starting Out with C++, 3rd Edition
Program continues
//***********************************************
// Definition of function showValues. *
// This function displays the contents of the *
// array passed into nums. The value passed *
// into elements is the number of elements in *
// the nums array. *
//***********************************************
59
Starting Out with C++, 3rd Edition
Program Output
5 10 15 20 25 30 35 40
2468
1 2 3 4 5 6 7 8 9 10 11 12
60
Starting Out with C++, 3rd Edition
Program 7-17
// This program uses a function that doubles the contents of
// the elements within an array.
#include <iostream.h>
void main(void)
{
int set[arraySize] = {1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12};
cout << "The arrays values are:\n";
for (int index = 0; index < arraySize; index++)
cout << set[index] << " ";
cout << endl;
doubleArray(set, arraySize);
cout << "After calling doubleArray, the values are:\n";
61
Starting Out with C++, 3rd Edition
Program continues
for (int index = 0; index < arraySize; index++)
cout << set[index] << " ";
cout << endl;
}
//**************************************************
// Definition of function doubleArray. *
// This function doubles the value of each element *
// in the array passed into nums. *
// The value passed into size is the number of *
// elements in the nums array. *
//**************************************************
void doubleArray(int nums[], int size)
{
for (int index = 0; index < size; index++)
nums[index] *= 2;
}
62
Starting Out with C++, 3rd Edition
Program Output
63
Starting Out with C++, 3rd Edition
7.10 Two-dimensional Arrays
64
Starting Out with C++, 3rd Edition
Program 7-18
// This program demonstrates a two-dimensional array.
#include <iostream.h>
void main(void)
{
float sales[3][4]; // 2D array, 3 rows and 4 columns.
float totalSales = 0; // To hold the total sales.
int dir, qtr; // Loop counters.
65
Starting Out with C++, 3rd Edition
Program continues
cout << "This program will calculate the total sales of\n";
cout << "all the company's divisions.\n";
cout << "Enter the following sales information:\n\n";
66
Starting Out with C++, 3rd Edition
Program continues
// Nested loops to add all the elements.
for (div = 0; div < 3; div++)
for (qtr = 0; qtr < 4; qtr++)
totalSales += sales[div][qtr];
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << "The total sales for the company are: $";
cout << totalSales << endl;
}
67
Starting Out with C++, 3rd Edition
Program Output with Example Input
This program will calculate the total sales of
all the company's divisions.
Enter the following sales information:
68
Starting Out with C++, 3rd Edition
Output continues
69
Starting Out with C++, 3rd Edition
Passing Two-dimensional Arrays to
Functions
• When a two-dimensional array is
passed to a function, the parameter
type must contain a size declarator for
the number of columns.
70
Starting Out with C++, 3rd Edition
7.11 Arrays of Strings
• A two-dimensional array of characters can
be used as an array of C-strings.
71
Starting Out with C++, 3rd Edition
Program 7-20
// This program displays the number of days in each month.
// It uses a two-dimensional character array to hold the
// names of the months and an int array to hold the number
// of days.
#include <iostream.h>
void main(void)
{
char months[12][10] = {"January", "February", "March",
"April", "May", "June",
"July", "August", "September”,
"October", "November","December"};
int days[12] = { 31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31};
for (int count = 0; count < 12; count++)
{
cout << months[count] << " has ";
cout << days[count] << " days.\n";
}
} 72
Starting Out with C++, 3rd Edition
Program 7-20 (continued)
Program Output
January has 31 days.
February has 28 days.
March has 31 days.
April has 30 days.
May has 31 days.
June has 30 days.
July has 31 days.
August has 31 days.
September has 30 days.
October has 31 days.
November has 30 days.
December has 31 days.
73
Starting Out with C++, 3rd Edition
Three Dimensional Arrays and
Beyond
• C++ allows you to create arrays with
virtually any number of dimensions.
• Here is an example of a three-dimensional
array declaration:
float seat[3][5][8];
74
Starting Out with C++, 3rd Edition
7.14 Introduction to the STL
vector
• The Standard Template Library (or STL) is
a collection of data types and algorithms
that you may use in your programs. These
data types and algorithms are programmer-
defined. They are not part of the C++
language, but were created in addition to the
built-in data types.
75
Starting Out with C++, 3rd Edition
7.14 Introduction to the STL
vector
• The data types that are defined in the STL
are commonly called containers, because
they store and organize data.
• There are two types of containers in the
STL: sequence containers and associative
containers.
• The vector data type is a sequence
container.
76
Starting Out with C++, 3rd Edition
7.14 Introduction to the STL
vector
• A vector is like an array in the following
ways:
– A vector holds a sequence of values, or
elements.
– A vector stores its elements in contiguous
memory locations.
– You can use the array subscript operator [] to
read the individual elements in the vector
77
Starting Out with C++, 3rd Edition
7.14 Introduction to the STL
vector
• However, a vector offers several
advantages over arrays. Here are just a few:
– You do not have to declare the number of
elements that the vector will have.
– If you add a value to a vector that is already
full, the vector will automatically increase its
size to accommodate the new value.
– vectors can report the number of elements
they contain.
78
Starting Out with C++, 3rd Edition
Declaring a vector
• To use vectors in your program, you must
first #include the vector header file with
the following statement:
#include <vector>
80
Starting Out with C++, 3rd Edition
Declaring a vector
• Now you are ready to declare an actual
vector object. Here is an example:
vector<int> numbers;
81
Starting Out with C++, 3rd Edition
Declaring a vector
• You can declare a starting size, if you
prefer. Here is an example:
vector<int> numbers(10);
82
Starting Out with C++, 3rd Edition
Other examples of vector
Declarations
Declaration Format Description
83
Starting Out with C++, 3rd Edition
Storing and Retrieving Values in
a vector
• To store a value in an element that already
exists in a vector, you may use the array
subscript operator [].
84
Starting Out with C++, 3rd Edition
Program 7-23
// This program stores, in two vectors, the hours worked by 5
// employees, and their hourly pay rates.
#include <iostream.h>
#include <vector> // Needed to declare vectors
using namespace std;
void main(void)
{
vector<int> hours(5); // Declare a vector of 5 integers
vector<float> payRate(5); // Declare a vector of 5 floats
86
Starting Out with C++, 3rd Edition
Program 7-23 (continued)
Program Output with Example Input Shown in Bold
Enter the hours worked by 5 employees and their
hourly rates.
Hours worked by employee #1: 10 [Enter]
Hourly pay rate for employee #1: 9.75 [Enter]
Hours worked by employee #2: 15 [Enter]
Hourly pay rate for employee #2: 8.62 [Enter]
Hours worked by employee #3: 20 [Enter]
Hourly pay rate for employee #3: 10.50 [Enter]
Hours worked by employee #4: 40 [Enter]
Hourly pay rate for employee #4: 18.75 [Enter]
Hours worked by employee #5: 40 [Enter]
Hourly pay rate for employee #5: 15.65 [Enter]
Here is the gross pay for each employee:
Employee #1: $97.50
Employee #2: $129.30
Employee #3: $210.00
Employee #4: $750.00
Employee #5: $626.00
87
Starting Out with C++, 3rd Edition
Using the push_back Member
Function
• You cannot use the [] operator to access a
vector element that does not exist.
• To store a value in a vector that does not
have a starting size, or is already full, use
the push_back member function. Here is
an example:
numbers.push_back(25);
88
Starting Out with C++, 3rd Edition
Program 7-24
// This program stores, in two vectors, the hours worked by a specified
// number of employees, and their hourly pay rates.
#include <iostream.h>
#include <vector> // Needed to declare vectors
using namespace std;
void main(void)
{
vector<int> hours; // hours is an empty vector
vector<float> payRate; // payRate is an empty vector
int numEmployees; // The number of employees
89
Starting Out with C++, 3rd Edition
Program 7-24 (continued)
for (int index = 0; index < numEmployees; index++)
{
int tempHours; // To hold the number of hours entered
float tempRate; // To hold the payrate entered
91
Starting Out with C++, 3rd Edition
Determining the Size of a
vector
• Unlike arrays, vectors can report the number of elements
they contain. This is accomplished with the size member
function. Here is an example of a statement that uses the
size member function:
numValues = set.size();
92
Starting Out with C++, 3rd Edition
Determining the Size of a
vector
• Example:
93
Starting Out with C++, 3rd Edition
Program 7-25
// This program demonstrates the vector size
// member function.
#include <iostream.h>
#include <vector>
using namespace std;
// Function prototype
void showValues(vector<int>);
void main(void)
{
vector<int> values;
94
Starting Out with C++, 3rd Edition
Program 7-25 (continued)
//**************************************************
// Definition of function showValues. *
// This function accepts an int vector as its *
// argument. The value of each of the vector's *
// elements is displayed. *
//**************************************************
95
Starting Out with C++, 3rd Edition
Program 7-25 (continued)
Program Output
0
2
4
6
8
10
12
96
Starting Out with C++, 3rd Edition
Removing Elements from a
vector
• Use the pop_back member function to
remove the last element from a vector.
collection.pop_back();
97
Starting Out with C++, 3rd Edition
Program 7-26
// This program demosntrates the vector size member function.
#include <iostream.h>
#include <vector>
using namespace std;
void main(void)
{
vector<int> values;
98
Starting Out with C++, 3rd Edition
Program 7-26 (continued)
// Now remove another value from the vector
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
Program Output
The size of values is 3
Popping a value from the vector...
The size of values is now 2
Popping a value from the vector...
The size of values is now 1
Popping a value from the vector...
The size of values is now 0 99
Starting Out with C++, 3rd Edition
Clearing a vector
• To completely clear the contents of a
vector, use the clear member function.
Here is an example:
numbers.clear();
void main(void)
{
vector<int> values(100);
101
Starting Out with C++, 3rd Edition
Program 7-27 (continued)
Program Output
The values vector has 100 elements.
I will call the clear member function...
Now, the values vector has 0 elements.
102
Starting Out with C++, 3rd Edition
Detecting an Empty vector
• To determine if a vector is empty, use the
empty member function. The function
returns true if the vector is empty, and
false if the vector has elements stored
in it. Here is an example of its use:
if (set.empty())
cout << "No values in set.\n";
103
Starting Out with C++, 3rd Edition
Program 7-28
// This program demosntrates the vector's empty member function.
#include <iostream.h>
#include <vector>
using namespace std;
// Function prototype
float avgVector(vector<int>);
void main(void)
{
vector<int> values;
int numValues;
float average;
104
Starting Out with C++, 3rd Edition
Program 7-28 (continued)
for (int count = 0; count < numValues; count++)
{
int tempValue;
//*************************************************************
// Definition of function avgVector. *
// This function accepts an int vector as its argument. If *
// the vector contains values, the function returns the *
// average of those values. Otherwise, an error message is *
// displayed and the function returns 0.0. *
//*************************************************************
105
Starting Out with C++, 3rd Edition
Program 7-28 (continued)
float avgVector(vector<int> vect)
{
int total = 0; // accumulator
float avg; // average
106
Starting Out with C++, 3rd Edition
Program 7-28 (continued)
Program Output with Example Input Shown in Bold
107
Starting Out with C++, 3rd Edition
Summary of vector Member
Functions
Member Function Description
108
Starting Out with C++, 3rd Edition
Summary of vector Member
Functions
clear() Clears a vector of all its elements.
Example:
vect.clear();
The statement above removes all the elements from vect.
109
Starting Out with C++, 3rd Edition
Summary of vector Member
Functions
push_back(value) Stores a value in the last element of the vector. If the vector
is full or empty, a new element is created.
Example:
vect.push_back(7);
The statement above stores 7 in the last element of vect.
reverse() Reverses the order of the elements in the vector (the last
element becomes the first element, and the first element
becomes the last element.)
Example:
vect.reverse();
The statement above reverses the order of the element in
vect.
110
Starting Out with C++, 3rd Edition
Summary of vector Member
Functions
swap(vector2) Swaps the contents of the vector with the contents of vector2.
Example:
vect1.swap(vect2);
The statement above swaps the contents of vect1 and
vect2.
111
Starting Out with C++, 3rd Edition