2008 Pearson Education, Inc. All rights reserved. 1 7 7 Arrays and Vectors.
Chapter 09 - Vectors and Arrays
-
Upload
rodrigo-andres-fernandez -
Category
Documents
-
view
227 -
download
0
Transcript of Chapter 09 - Vectors and Arrays
-
8/12/2019 Chapter 09 - Vectors and Arrays
1/47
1
Chapter 9: Vectors and Arrays
Chapter Goals To become familiar with using vectors to
collect objects
To be able to access vector elementsand resize vectors
To be able to pass vectors to functions
To learn about common array
algorithms
To learn how to use one-dimensionaland two-dimensional arrays
-
8/12/2019 Chapter 09 - Vectors and Arrays
2/47
2
Using Vectors to Collect Data Items Suppose you write a program that read in a list of salary
figures and prints the list, marking the highest value, likethis:
32000
5400067500290003500080000
highest value => 1150004450010000065000
All the values need to be read to find the highest one.
If you know there are ten inputs, you could use 10variables salary1, salary2, ... , salary10.But you would have to write a lot of code ten times tohandle each variable.
This technique becomes prohibitive as the list gets larger(e.g., 100 salaries ).
-
8/12/2019 Chapter 09 - Vectors and Arrays
3/47
3
Using Vectors to Collect Data Items
A vectoris a collection of data items of the sametype.
vector salaries(10);
This vector holds 10 values, each of which are
double.
-
8/12/2019 Chapter 09 - Vectors and Arrays
4/47
4
Using Vectors to Collect Data Items
(Syntax 9.1 Vector Variable Definition)
Syntax
vectorvariable_namevector var_name(initial_size);
Example:
vector scores;
vector staff(20);
Purpose:
Define a new variable of vector type, andoptionally supply an initial size.
-
8/12/2019 Chapter 09 - Vectors and Arrays
5/47
5
Using Vectors to Collect Data Items
You must specify which slot you want touse with the [] operator.
Example:
salaries[4] = 35000;
The number inside the brackets is calledan index.
Because salaries is a vector of double
values, a slot such as salaries[4] can beused just like any variable of type double.
Example:cout
-
8/12/2019 Chapter 09 - Vectors and Arrays
6/47
6
Using Vectors to Collect Data Items
(cont.)
In C++, the slotsof vectors arenumbered starting
at 0.
-
8/12/2019 Chapter 09 - Vectors and Arrays
7/47
7
Syntax 9.2 : Vector Subscripts
General Syntaxvector_expression[integer_expression]
Example:
salaries[i + 1]
refers to the element in position givenby the value of expression i+1
Purpose:
Access and element in a vector.
-
8/12/2019 Chapter 09 - Vectors and Arrays
8/47
8
Vector Subscripts
Trying to access a slot that does not exist in the vector is
an error.
Example:vector staff(10);cout
-
8/12/2019 Chapter 09 - Vectors and Arrays
9/47
9
Vector Subscripts You can find the size vector by calling the size
function.for(i = 0; i < v.size(); i++)do something withv[i];
The function push_back allows you to start out
with an empty vector and grow the vectorwhenever another element is added.
vector salaries;
. . .
double s;
cin >> s;
. . .
salaries.push_back(s);
-
8/12/2019 Chapter 09 - Vectors and Arrays
10/47
10
Vector Subscripts (cont.)
The push_back command resizes the vector by
adding one element to its end.
If you already know how many elements youneed in a vector, you should specify that sizewhen you define it.
Another member function, pop_back, removesthe last element of a vector, shrinking its size byone.
salaries.pop_back();
/* Now salaries has size 9 */
The standard defines many more useful functionsfor vectors; in this book, we only use push_back
and pop_back.
-
8/12/2019 Chapter 09 - Vectors and Arrays
11/47
11
Vector Subscripts (salvect.cpp)01: #include02: #include
03:04: usingnamespacestd;05:06: intmain() {08: vector salaries;09: bool more = true;10: while(more) {12: double s;13: cout > s;15: if(s == 0)
16: more = false;17: else18: salaries.push_back(s);19: }20:21: double highest = salaries[0];22: int i;23: for(i = 1; i < salaries.size(); i++)24: if(salaries[i] > highest)25: highest = salaries[i];26:
27: for(i = 0; i < salaries.size(); i++) {29: if(salaries[i] == highest)30: cout
-
8/12/2019 Chapter 09 - Vectors and Arrays
12/47
12
Vector Parameters and Return Values
(Vector Parameters)
Functions and procedures often have vector parameters.Example:
double average(vector v) {if (v.size() == 0) return 0;
double sum = 0;
for (int i = 0; i < v.size(); i++)
sum = sum + v[i];return sum / v.size();
}
A vector can be passed by value or by reference.
Pass by reference is used for modifying individual elements of the
vector.
Example:void raise_by_percent(vector& v, double p){
for (int i = 0; i < v.size(); i++)
v[i] =v[i] * (1 + p / 100);
}
-
8/12/2019 Chapter 09 - Vectors and Arrays
13/47
-
8/12/2019 Chapter 09 - Vectors and Arrays
14/47
14
Vector Parameters and Return Values
(Return Values) (cont.)
Here is a function that collects thepositions of all matching values in a vectorof integers.
vector find_all_between(vector v,double low, double high){
vector pos;
for (int i = 0; i < v.size(); i++) {
if (low
-
8/12/2019 Chapter 09 - Vectors and Arrays
15/47
15
Vector Parameters and Return
Values (matches.cpp)
25: intmain() {27: vector salaries(5);28: salaries[0] = 35000.0;29: salaries[1] = 63000.0;30: salaries[2] = 48000.0;31: salaries[3] = 78000.0;32: salaries[4] = 51500.0;33:34: vector matches =
find_all_between(salaries, 45000.0,65000.0);
36:37: for(int j = 0; j < matches.size(); j++)38: cout
-
8/12/2019 Chapter 09 - Vectors and Arrays
16/47
16
Removing and Inserting Elements
How do you remove an element froma vector?
If the order is notimportant,overwrite the element to be removed
with the lastelement of the vector,then shrink the size of the vector.
Example:
void erase(vector& v, int pos){int last_pos = v.size() - 1;v[pos] = v[last_pos];v.pop_back();
}
-
8/12/2019 Chapter 09 - Vectors and Arrays
17/47
17
Example of Element Removal
-
8/12/2019 Chapter 09 - Vectors and Arrays
18/47
18
Removing and Inserting Elements
If the order matters, you must move all
elements down by one slot, then shrinkthe size of the vector.
void erase(vector& v, int pos) {for (int i=pos; i
-
8/12/2019 Chapter 09 - Vectors and Arrays
19/47
-
8/12/2019 Chapter 09 - Vectors and Arrays
20/47
-
8/12/2019 Chapter 09 - Vectors and Arrays
21/47
21
Removing and Inserting Elements
Note that when you insert an element you start at the end of the
vector, move that element up, then go to the one before that.
-
8/12/2019 Chapter 09 - Vectors and Arrays
22/47
22
Parallel Vectors
Suppose you want to process a series of product
data, and then display the product information,making the best value (with the best price/score
ratio).ACMA P600 Price: 995 Score75
ALaris Nx686 Price 798 Score 57
AMAX Powerstation 600 Price: 999 Score 75
AMS Infogold P600 Price: 795 Score: 69
AST PRemmia Price: 2080 Score: 80
Austin 600 Price: 1499 Score: 95
best value => Blackship NX-600 Price 598 Score: 60
Kompac 690 Price: 695 Score: 60
One possibility is to create three vectors (names,price, scores) of the same length. (Seebestval1.cpp)
These vectors are calledparallelvectorsbecause
they must be processed together.
-
8/12/2019 Chapter 09 - Vectors and Arrays
23/47
23
Parallel Vectors (cont.)
Each slice- names[i], prices[i], scores[i] - contains data
that needs to be processed together.
-
8/12/2019 Chapter 09 - Vectors and Arrays
24/47
24
Parallel Vectors (bestval1.cpp)
01: #include
02: #include03: #include04:05: usingnamespacestd;06:
07: intmain() {09: vector names;10: vector prices;11: vector scores;12:13: double best_price = 1;14: int best_score = 0;15: int best_index = -1;
16:17: bool more = true;
47:
-
8/12/2019 Chapter 09 - Vectors and Arrays
25/47
25
bestval1.cpp (cont.)18: while(more) {20: string next_name;
21: cout next_price;
27: prices.push_back(next_price);28: int next_score;
29: cout > next_score;31: scores.push_back(next_score);32: string remainder; /* read remainder of line */
33: getline(cin, remainder);34:
35: if(next_score / next_price > best_score / best_price) {37: best_index = names.size() - 1;
38: best_score = next_score;39: best_price = next_price;
40: }
41:
42: cout
-
8/12/2019 Chapter 09 - Vectors and Arrays
26/47
26
bestval1.cpp (cont.)
48: for(int i = 0; i < names.size(); i++) {50: if(i == best_index)
cout
-
8/12/2019 Chapter 09 - Vectors and Arrays
27/47
27
Parallel Vectors
Parallel vectors become a headache inlarger programs. Each vector must be the same length. Each slice is filled with values that belong
together.
Any function that operates on a slice must getseveral vectors as parameters.
To remove parallel vectors, look at theslice and find the conceptit represents.
Make the concept into a class. Eliminate parallel vectors and replace
them with a single vector.
P ll l V t Eli i ti
-
8/12/2019 Chapter 09 - Vectors and Arrays
28/47
28
Parallel Vectors Elimination Use a class to represent the type of element
represented in the parallel vectors and use an
array or vector of that type of element.
-
8/12/2019 Chapter 09 - Vectors and Arrays
29/47
29
Example : Class Product012: classProduct {014: public:015: /**016: Constructs a product with zero price and score.017: */018: Product();019:020: /**021: Reads in this product object.022: */023: void read();
024:025: /**026: Compares two product objects.027: @param b the object to compare with this object028: @retur true if this object is better than b029: */030: bool is_better_than(Product b) const;031:
032: /**033: Print this product object034: */035: void print() const;036: private:037: string name;038: double price;039: int score;
040: };
-
8/12/2019 Chapter 09 - Vectors and Arrays
30/47
30
Class Product (cont.)042: Product::Product()043: {044: price = 0;
045: score = 0;046: }047:048: void Product::read() {050: cout price;054: cout > score;056: string remainder;/* read remainder of line */057: getline(cin, remainder);058: }059:060: bool Product::is_better_than(Product b) const {062: if(price == 0) returnfalse;063: if(b.price == 0) returntrue;
064: returnscore / price > b.score / b.price;065: }066:067: void Product::print() const {069: cout
-
8/12/2019 Chapter 09 - Vectors and Arrays
31/47
31
New Version of bestval.cpp074: int main() {076: vector products;077:078: Product best_product;079: int best_index = -1;080:081: bool more = true;082: while(more) {084: Product next_product;085: next_product.read();086: products.push_back(next_product);087:
088: if(next_product.is_better_than(best_product))089: {090: best_index = products.size() - 1;091: best_product = next_product;092: }093:094: cout
-
8/12/2019 Chapter 09 - Vectors and Arrays
32/47
32
Arrays
A second mechanism for collecting
elements of the same type is using arrays.
Arrays are a lower-level abstraction thanvectors, so they are less convenient.
Example: Arrays cannot be resized.
Vectors are a recent addition to C++, somany older programs use arrays instead.
Arrays are faster and more efficient thanvectors.
-
8/12/2019 Chapter 09 - Vectors and Arrays
33/47
33
Arrays
Declaring an array is very similar to declaring a
vector. Array declaration : double salaries[10]; Vector declaration : vector salaries(10);
Arrays can never change size size is fixed in declaration
The array size must be set when the program iscompiled. (You can't ask the user how manyelements and then allocate a sufficient number).
When defining an array, you must guess on themaximum number of elements you need to store.
const int SALARIES_CAPACITY = 100;
double salaries[SALARIES_CAPACITY];
A
-
8/12/2019 Chapter 09 - Vectors and Arrays
34/47
34
Arrays You must keep a constant to hold the capacityof the array.
You must keep a companion variablethat counts how manyelements are actually used.
Example:
int salaries_size = 0;while (more && salaries_size < SALARIES_CAPACITY){
cout > x;if (cin.fail() || x == 0)
more = false;else {
salaries[salaries_size] = x;
salaries_size++;}}
-
8/12/2019 Chapter 09 - Vectors and Arrays
35/47
35
Arrays (Syntax 9.3: Array Variable Definition)
Array Variable Definitiontype_name variable_name[size];
Example:int scores[20];
Purpose:
Define a new variable of an array
type.
Array Parameters
-
8/12/2019 Chapter 09 - Vectors and Arrays
36/47
36
Array Parameters When writing a function with an array parameter, you place an
empty[] behind the parameter name:
Example: double maximum(double a[], int a_size);
You need to pass the size of the array into the function, because thefunction has no other way of querying the size of the array (there isno size() member function)
Unlike all other parameters, array parameters are always passed byreference.
Example: alter each of the first s_size elements of s
void raise_by_percent(double s[],double s_size,double p) {
int i;
for (i = 0; i < s_size; i++)
s[i] = s[i] * (1 + p / 100);
}
Never use an & when defining an array parameter.
Use the const keyword whenever a function does not actually modifyan array.Example: double maximum(const double a[], int a_size)
Array Parameters
-
8/12/2019 Chapter 09 - Vectors and Arrays
37/47
37
Array Parameters If a function adds elements to an array, you need to pass
the array, the maximum size, and the current size.
The current size must be passed as a reference parameter.
Example:void read_data(double a[], int a_capacity,
int& a_size) {
a_size = 0;
while (a_size < a_capacity) {double x;
cin >> x;
if (cin.fail()) return;
a[a_size] = x;
a_size++;
}}
Arrays cannot be function return types.
To "return" an array, the caller of the function must provide
an array parameter to hold the result.
-
8/12/2019 Chapter 09 - Vectors and Arrays
38/47
-
8/12/2019 Chapter 09 - Vectors and Arrays
39/47
39
Example: max value in an array
/**
Computes the maximum value in an array@param a the array@param a_size the number of values in a
*/
double maximum(constdouble a[], int a_size) {if(a_size == 0) return0;
double highest = a[0];for(int i = 1; i < a_size; i++)
if(a[i] > highest)highest = a[i];
returnhighest;}
Ch t A
-
8/12/2019 Chapter 09 - Vectors and Arrays
40/47
40
Character Arrays There was a time when C++ had no string class.
All string processing was carried out by manipulating arrays of the type
char.
The char type denotes an individual character and is delimited by singlequotes.Example:
char input = 'y';// don't confuse with "y
A character array is used to hold a string.Example:
char g[] = "Hello";// same as g[6] = "Hello
The array occupies size characters - one for each letter and azeroterminator.
g[0] g[1] g[2] g[3] g[4] g[5]
You do not need to specify the size of the array variable for a characterarray constant.
H e l l o \0
Ch t A
-
8/12/2019 Chapter 09 - Vectors and Arrays
41/47
41
Character Arrays
Many string functions in the standard library depend on zeroterminators in character arrays.
Example:int strlen(const char s[]) {
int i = 0;
while (s[i] != '\0')
i++;
return i;
}
It's important to not forget the space for the zeroterminator. (null character)
It's helpful to declare character arrays with an "extra space"for the zero terminator.
Example:const int MYSTRING_MAXLENGTH = 4;char mystring[MYSTRING_MAXLENGTH + 1];
d t
-
8/12/2019 Chapter 09 - Vectors and Arrays
42/47
42
Example: append 2ndto 1ststring
/**Appends as much as possible from a string to another
string@param s the string to which t is appended@param s_maxlength the maximum length of s (not
counting '\0')@param t the string to append
*/void append(char s[], int s_maxlength, constchar t[]) {int i = strlen(s);int j = 0;/* append t to s */while(t[j] != '\0' and i < s_maxlength) {
s[i] = t[j];i++;j++;}/* add zero terminator */s[i] = '\0';
}
Ch t A
-
8/12/2019 Chapter 09 - Vectors and Arrays
43/47
43
Character Arrays
Generally it is best to avoid the use of characterarrays - the string class is safer and far moreconvenient.
Occasionally you need to convert a string into acharacter array to call a function that was writtenbefore the string class was invented.
Example: to convert a character array containingdigits into its integer value.
int atoi(const char s[])
Use the c_str member function to convert a
string into a character array.Example:
string year = "1999";
int y = atoi(year.c_str());
-
8/12/2019 Chapter 09 - Vectors and Arrays
44/47
44
Two-Dimensional Arrays
It often happens that we want to store collections
of numbers that have a two-dimensional layout. Such an arrangement, consisting of row and
columns of values, is called a two-dimensionalarray, or a matrix.
C++ uses an array with two subscripts to store atwo-dimensional array:Example:
const int BALANCE_ROWS = 11;
const int BALANCE_COLS = 6;
double balances[BALANCE_ROWS][BALANCE_COLS];
To select a particular element in the two-dimensional array, we need to specify twosubscripts in separate brackets to select the rowand column.
-
8/12/2019 Chapter 09 - Vectors and Arrays
45/47
45
Accessing an Element in 2-dim array
-
8/12/2019 Chapter 09 - Vectors and Arrays
46/47
46
Two-Dimensional Array Definition
Syntax Two-Dimensional Array Definitiontype_name variable_name[size1][size2];
Example:
double monthly_sales[NREGIONS][12];
Purpose:
Define a new variable that is a two-dimensional array.
T Di i l A
-
8/12/2019 Chapter 09 - Vectors and Arrays
47/47
Two-Dimensional Arrays
When passing a two-dimensional array to
a function, you must specify the numberof columns as a constantwith theparameter type.
The number of rows can be variable.void print_table(const double table[][BALANCE_COLS], int table_rows) {
const int WIDTH = 10;
cout