1 Chapter 9: Vectors and Chapter 9: Vectors and Arrays Arrays Chapter Goals Chapter Goals • To become familiar with using To become familiar with using vectors to collect objects vectors to collect objects • To be able to access vector To be able to access vector elements and resize vectors elements and resize vectors • To be able to pass vectors to To be able to pass vectors to functions functions • To learn about common array To learn about common array algorithms algorithms • To learn how to use one-dimensional To learn how to use one-dimensional and two-dimensional arrays and two-dimensional arrays
47
Embed
1 Chapter 9: Vectors and Arrays Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
11
Chapter 9: Vectors and Arrays Chapter 9: Vectors and Arrays
Chapter GoalsChapter Goals• To become familiar with using vectors to To become familiar with using vectors to
collect objects collect objects • To be able to access vector elements To be able to access vector elements
and resize vectors and resize vectors • To be able to pass vectors to functions To be able to pass vectors to functions • To learn about common array To learn about common array
algorithms algorithms • To learn how to use one-dimensional To learn how to use one-dimensional
and two-dimensional arrays and two-dimensional arrays
22
Using Vectors to Collect Data ItemsUsing Vectors to Collect Data Items Suppose you write a program that read in a list of salary Suppose you write a program that read in a list of salary
figures and prints the list, marking the highest value, like figures and prints the list, marking the highest value, like this: this:
highest value => 115000 highest value => 115000 44500 44500 100000 100000 65000 65000
All the values need to be read to find the highest one. All the values need to be read to find the highest one.
If you know there are ten inputs, you could use 10 variables If you know there are ten inputs, you could use 10 variables salary1, salary2, ... , salary10salary1, salary2, ... , salary10. . But you would have to write a lot of code ten times to But you would have to write a lot of code ten times to handle each variable. handle each variable.
This technique becomes prohibitive as the list gets larger This technique becomes prohibitive as the list gets larger (e.g., 100 salaries …). (e.g., 100 salaries …).
33
Using Vectors to Collect Data ItemsUsing Vectors to Collect Data Items
A A vectorvector is a collection of data items of the same is a collection of data items of the same type. type.
vector<double> salaries(10); vector<double> salaries(10); This vector holds 10 values, each of which are This vector holds 10 values, each of which are
double. double.
44
Using Vectors to Collect Data Items Using Vectors to Collect Data Items
PurposePurpose: : Define a new variable of vector type, and Define a new variable of vector type, and optionally supply an initial size.optionally supply an initial size.
55
Using Vectors to Collect Data ItemsUsing Vectors to Collect Data Items
You must specify which slot you want to You must specify which slot you want to use with the [] operator. use with the [] operator.
ExampleExample::
salaries[4] = 35000; salaries[4] = 35000; The number inside the brackets is called The number inside the brackets is called
an an index.index. Because salaries is a vector of double Because salaries is a vector of double
values, a slot such as salaries[4] can be values, a slot such as salaries[4] can be used just like any variable of type double. used just like any variable of type double.
General SyntaxGeneral Syntax vector_expressionvector_expression[[integer_expressioninteger_expression]]
ExampleExample: :
salaries[i + 1] salaries[i + 1] • refers to the element in position given refers to the element in position given
by the value of expression i+1by the value of expression i+1
PurposePurpose: : Access and element in a vector.Access and element in a vector.
88
Vector SubscriptsVector Subscripts Trying to access a slot that does not exist in the vector is an Trying to access a slot that does not exist in the vector is an
/* legal subscripts are 0 until 9 */ /* legal subscripts are 0 until 9 */
The C++ standard implementation of vector generates The C++ standard implementation of vector generates nono error message. error message.
If you make an index error, you silently read or overwrite If you make an index error, you silently read or overwrite another memory location. another memory location.
When a vector is defined without a size parameter, it is When a vector is defined without a size parameter, it is empty and can hold empty and can hold nono elements. elements.
ExampleExample: : vector<double> salaries; /* no size given */ vector<double> salaries; /* no size given */ salaries[0] = 35000; salaries[0] = 35000;
99
Vector SubscriptsVector Subscripts You can find the size vector by calling the size You can find the size vector by calling the size
function. function. for(i = 0; i < v.size(); i++)for(i = 0; i < v.size(); i++)
do something withdo something with v[i]; v[i];
The function push_back allows you to start out The function push_back allows you to start out with an empty vector and grow the vector with an empty vector and grow the vector whenever another element is added. whenever another element is added.
The push_back command resizes the vector by The push_back command resizes the vector by adding one element to its end. adding one element to its end.
If you already know how many elements you If you already know how many elements you need in a vector, you should specify that size need in a vector, you should specify that size when you define it. when you define it.
Another member function, pop_back, removes the Another member function, pop_back, removes the last element of a vector, shrinking its size by one. last element of a vector, shrinking its size by one.
salaries.pop_back(); salaries.pop_back(); /* Now salaries has size 9 */ /* Now salaries has size 9 */
The standard defines many more useful functions The standard defines many more useful functions for vectors; in this book, we only use push_back for vectors; in this book, we only use push_back and pop_back. and pop_back.
1111
Vector Subscripts (salvect.cpp)Vector Subscripts (salvect.cpp) 01: 01: #include#include <iostream> <iostream> 02: 02: #include#include <vector> <vector> 03: 03: 04: 04: usingusing namespacenamespace std; std; 05: 05: 06: int 06: int mainmain() { () { 08: vector<double> salaries; 08: vector<double> salaries; 09: bool more = 09: bool more = truetrue;; 10: 10: whilewhile (more) { (more) { 12: double s; 12: double s; 13: cout << "Please enter a salary, 0 to quit: "; 13: cout << "Please enter a salary, 0 to quit: "; 14: cin >> s; 14: cin >> s; 15: 15: ifif (s == 0) (s == 0) 16: more = 16: more = falsefalse;; 17: 17: elseelse 18: salaries. 18: salaries.push_backpush_back(s);(s); 19: } 19: } 20: 20: 21: double highest = salaries[0]; 21: double highest = salaries[0]; 22: int i; 22: int i; 23: 23: forfor (i = 1; i < salaries. (i = 1; i < salaries.sizesize(); i++)(); i++) 24: 24: ifif (salaries[i] > highest) (salaries[i] > highest) 25: highest = salaries[i]; 25: highest = salaries[i]; 26: 26: 27: 27: forfor (i = 0; i < salaries. (i = 0; i < salaries.sizesize(); i++) { (); i++) { 29: 29: ifif (salaries[i] == highest) (salaries[i] == highest) 30: 30: cout << "highest value => "; cout << "highest value => "; 31: 31: cout << salaries[i] << "\n"; cout << salaries[i] << "\n"; 32: 32: } } 34: 34: returnreturn 0; 0; 35: } 35: }
1212
Vector Parameters and Return Values Vector Parameters and Return Values (Vector Parameters)(Vector Parameters)
Functions and procedures often have vector parameters. Functions and procedures often have vector parameters.
ExampleExample: : double average(vector<double> v) { double average(vector<double> v) { if (v.size() == 0) return 0; if (v.size() == 0) return 0; double sum = 0; double sum = 0; for (int i = 0; i < v.size(); i++) for (int i = 0; i < v.size(); i++) sum = sum + v[i]; sum = sum + v[i]; return sum / v.size(); return sum / v.size(); } }
A vector can be passed by value or by reference. A vector can be passed by value or by reference.
Pass by reference is used for modifying individual elements of the Pass by reference is used for modifying individual elements of the vector. vector.
p){ p){ for (int i = 0; i < v.size(); i++) for (int i = 0; i < v.size(); i++)
v[i] =v[i] * (1 + p / 100); v[i] =v[i] * (1 + p / 100); } }
1313
Vector Parameters and Return Vector Parameters and Return Values (Return Values) Values (Return Values)
A function can return a vector. A function can return a vector. Here is a function that collects all values Here is a function that collects all values
that fall within a certain range. that fall within a certain range.
vector<double> between(vector<double> v, vector<double> between(vector<double> v, double low, double high){ double low, double high){ vector<double> result; vector<double> result; for (int i = 0; i < v.size(); i++) for (int i = 0; i < v.size(); i++) if (low <= v[i] && v[i] <= high) if (low <= v[i] && v[i] <= high) result.push_back(v[i]); result.push_back(v[i]); return result; return result;} }
1414
Vector Parameters and Return Values Vector Parameters and Return Values (Return Values) (cont.)(Return Values) (cont.)
Here is a function that collects the Here is a function that collects the positions of all matching values in a vector positions of all matching values in a vector of integers. of integers. vector<int> find_all_between(vector<double> v,vector<int> find_all_between(vector<double> v, double low, double high){double low, double high){ vector<int> pos; vector<int> pos; for (int i = 0; i < v.size(); i++) { for (int i = 0; i < v.size(); i++) { if (low <= v[i] && v[i] <= high) if (low <= v[i] && v[i] <= high) pos.push_back(i); pos.push_back(i); } } return pos; return pos;} }
1515
Vector Parameters and Return Vector Parameters and Return Values (matches.cpp)Values (matches.cpp)
Removing and Inserting ElementsRemoving and Inserting Elements How do you remove an element from How do you remove an element from
a vector? a vector? If the order is If the order is notnot important, important,
overwrite the element to be removed overwrite the element to be removed with the with the lastlast element of the vector, element of the vector, then shrink the size of the vector.then shrink the size of the vector.
ExampleExample::void erase(vector<string>& v, int pos){void erase(vector<string>& v, int pos){ int last_pos = v.size() - 1; int last_pos = v.size() - 1; v[pos] = v[last_pos]; v[pos] = v[last_pos]; v.pop_back(); v.pop_back();}}
17
Example of Element Removal
1818
Removing and Inserting ElementsRemoving and Inserting Elements If the order matters, you must move all If the order matters, you must move all
elements down by one slot, then shrink elements down by one slot, then shrink the size of the vector. the size of the vector.
void erase(vector<string>& v, int pos) {void erase(vector<string>& v, int pos) { for (int i=pos; i<v.size()-1; i++) for (int i=pos; i<v.size()-1; i++) v[i] = v[i+1]; v[i] = v[i+1];
v.pop_back();v.pop_back();} }
19
Removing and Inserting Elements
2020
Removing and Inserting ElementsRemoving and Inserting Elements
To insert an insert an element in the middle of a To insert an insert an element in the middle of a vector, you must add a new element at the end of vector, you must add a new element at the end of the vector and move all elements above the the vector and move all elements above the insertion location up by one slot. insertion location up by one slot.
void insert(vector<string>& v,void insert(vector<string>& v, int pos, string s) { int pos, string s) {
int last = v.size() - 1; int last = v.size() - 1; v.push_back(v[last]); v.push_back(v[last]);
for (int i = last; i > pos; i--) for (int i = last; i > pos; i--) v[i] = v[i - 1]; v[i] = v[i - 1]; v[pos] = s; v[pos] = s;
} }
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.
2222
Parallel VectorsParallel Vectors Suppose you want to process a series of product Suppose you want to process a series of product
data, and then display the product information, data, and then display the product information, making the best value (with the best price/score making the best value (with the best price/score ratio).ratio).
One possibility is to create three vectors (names, One possibility is to create three vectors (names, price, scores) of the same length. (See price, scores) of the same length. (See bestval1.cpp) bestval1.cpp)
These vectors are called These vectors are called parallelparallel vectorsvectors because because they must be processed together. they must be processed together.
23
Parallel Vectors (cont.)
• Each slice - names[i], prices[i], scores[i] - contains data that needs to be processed together.
Parallel VectorsParallel Vectors Parallel vectors become a headache in Parallel vectors become a headache in
larger programs. larger programs. • Each vector must be the same length. Each vector must be the same length. • Each slice is filled with values that belong Each slice is filled with values that belong
together. together. • Any function that operates on a slice must get Any function that operates on a slice must get
several vectors as parameters. several vectors as parameters.
To remove parallel vectors, look at the To remove parallel vectors, look at the slice and find the slice and find the conceptconcept it represents. it represents. Make the concept into a class. Make the concept into a class.
Eliminate parallel vectors and replace Eliminate parallel vectors and replace them with a single vector. them with a single vector.
2828
Parallel Vectors EliminationParallel Vectors Elimination Use a class to represent the type of element Use a class to represent the type of element
represented in the parallel vectors and use an represented in the parallel vectors and use an array or vector of that type of element. array or vector of that type of element.
2929
Example : Class Example : Class ProductProduct 012: 012: classclass Product { Product { 014: 014: publicpublic:: 015: 015: /**/** 016: 016: Constructs a product with zero price and score. Constructs a product with zero price and score. 017: 017: */ */ 018: 018: ProductProduct();(); 019: 019: 020: 020: /**/** 021: 021: Reads in this product object. Reads in this product object. 022: 022: */ */ 023: void 023: void readread();(); 024: 024: 025: 025: /**/** 026: 026: Compares two product objects. Compares two product objects. 027: 027: @param b the object to compare with this object @param b the object to compare with this object 028: 028: @retur true if this object is better than b @retur true if this object is better than b 029: 029: */ */ 030: bool 030: bool is_better_thanis_better_than(Product b) (Product b) constconst;; 031: 031: 032: 032: /**/** 033: 033: Print this product object Print this product object 034: 034: */ */ 035: void 035: void printprint() () constconst;; 036: 036: privateprivate:: 037: string name; 037: string name; 038: double price; 038: double price; 039: int score; 039: int score; 040: }; 040: };
ArraysArrays A second mechanism for collecting A second mechanism for collecting
elements of the same type is using elements of the same type is using arraysarrays..
Arrays are a lower-level abstraction than Arrays are a lower-level abstraction than vectors, so they are less convenient. vectors, so they are less convenient. • Example: Arrays cannot be resized. Example: Arrays cannot be resized.
Vectors are a recent addition to C++, so Vectors are a recent addition to C++, so many older programs use arrays instead. many older programs use arrays instead.
Arrays are faster and more efficient than Arrays are faster and more efficient than vectors. vectors.
3333
ArraysArrays Declaring an array is very similar to declaring a Declaring an array is very similar to declaring a
Arrays can never change size Arrays can never change size • size is fixed in declarationsize is fixed in declaration
The array size must be set The array size must be set when the program is when the program is compiledcompiled. (You can't ask the user how many . (You can't ask the user how many elements and then allocate a sufficient number).elements and then allocate a sufficient number).
When defining an array, you must guess on the When defining an array, you must guess on the maximum number of elements you need to store. maximum number of elements you need to store.
const int SALARIES_CAPACITY = 100; const int SALARIES_CAPACITY = 100; double salaries[SALARIES_CAPACITY]; double salaries[SALARIES_CAPACITY];
3434
ArraysArrays You must keep a constant to hold the You must keep a constant to hold the capacitycapacity of the array. of the array.
You must keep a You must keep a companion variablecompanion variable that counts how many that counts how many elements are actually elements are actually usedused. .
ExampleExample: :
int salaries_size = 0;int salaries_size = 0;while (more && salaries_size < SALARIES_CAPACITY){while (more && salaries_size < SALARIES_CAPACITY){ cout << "Enter salary or 0 to quit: "; cout << "Enter salary or 0 to quit: "; double x; double x; cin >> x; cin >> x; if (cin.fail() || x == 0) if (cin.fail() || x == 0) more = false; more = false; else { else { salaries[salaries_size] = x; salaries[salaries_size] = x; salaries_size++; salaries_size++; } } } }
Define a new variable of an arrayDefine a new variable of an array
type.type.
3636
Array ParametersArray Parameters When writing a function with an array parameter, you place an When writing a function with an array parameter, you place an
empty[] behind the parameter name: empty[] behind the parameter name:
• ExampleExample: : double maximum(double a[], int a_size); double maximum(double a[], int a_size);
You need to pass the size of the array into the function, because the You need to pass the size of the array into the function, because the function has no other way of querying the size of the array (there is function has no other way of querying the size of the array (there is no size() member function) no size() member function)
Unlike all other parameters, array parameters are always passed by Unlike all other parameters, array parameters are always passed by reference. reference.
ExampleExample: … alter each of the first s_size elements of s: … alter each of the first s_size elements of s
void raise_by_percent(double s[],double s_size,double p) {void raise_by_percent(double s[],double s_size,double p) { int i; int i;
for (i = 0; i < s_size; i++) for (i = 0; i < s_size; i++) s[i] = s[i] * (1 + p / 100); s[i] = s[i] * (1 + p / 100);
} }
Never use an & when defining an array parameter. Never use an & when defining an array parameter.
Use the const keyword whenever a function does not actually modify Use the const keyword whenever a function does not actually modify an array. an array. ExampleExample: : double maximum(const double a[], int a_size) double maximum(const double a[], int a_size)
3737
Array Parameters If a function adds elements to an array, you need to pass If a function adds elements to an array, you need to pass
the array, the maximum size, and the current size. the array, the maximum size, and the current size.
The current size must be passed as a reference parameter. The current size must be passed as a reference parameter.
• ExampleExample: : void read_data(double a[], int a_capacity, void read_data(double a[], int a_capacity,
Arrays cannot be function return types. Arrays cannot be function return types.
To "return" an array, the caller of the function must provide To "return" an array, the caller of the function must provide an array parameter to hold the result. an array parameter to hold the result.
3838
Example: reads data into an arrayExample: reads data into an array/**/**
Reads data into an array.Reads data into an array. @param a the array to fill@param a the array to fill @param a_capacity the maximum size of a@param a_capacity the maximum size of a @param a_size filled with the size of a after reading @param a_size filled with the size of a after reading
*/*/ void void read_dataread_data(double a[], int a_capacity, int& a_size) {(double a[], int a_capacity, int& a_size) {
forfor (int i = 1; i < a_size; i++) (int i = 1; i < a_size; i++) ifif (a[i] > highest) (a[i] > highest) highest = a[i]; highest = a[i];
returnreturn highest; highest;
}}
4040
Character ArraysCharacter Arrays There was a time when C++ had no string class. There was a time when C++ had no string class.
All string processing was carried out by manipulating arrays of the type All string processing was carried out by manipulating arrays of the type char. char.
The char type denotes an individual character and is delimited by single The char type denotes an individual character and is delimited by single quotes. quotes. ExampleExample: :
char input = 'y'; char input = 'y'; // don't confuse with "y“// don't confuse with "y“
A character array is used to hold a string. A character array is used to hold a string. ExampleExample: :
char g[] = "Hello"; char g[] = "Hello"; // same as g[6] = "Hello“// same as g[6] = "Hello“
The array occupies size characters - one for each letter and a The array occupies size characters - one for each letter and a zerozero terminatorterminator. .
You do not need to specify the size of the array variable for a character You do not need to specify the size of the array variable for a character array constant. array constant.
‘‘H’H’ ‘‘e’e’ ‘‘l’l’ ‘‘l’l’ ‘‘o’o’ ‘‘\0’\0’
4141
Character ArraysCharacter Arrays Many string functions in the standard library depend on zero Many string functions in the standard library depend on zero
terminators in character arrays. terminators in character arrays.
ExampleExample: : int strlen(const char s[]) { int strlen(const char s[]) { int i = 0; int i = 0; while (s[i] != '\0') while (s[i] != '\0')
i++; i++; return i; return i; } }
It's important to not forget the space for the zero terminator. It's important to not forget the space for the zero terminator. (null character)(null character)
It's helpful to declare character arrays with an "extra space" It's helpful to declare character arrays with an "extra space" for the zero terminator. for the zero terminator.
ExampleExample: : const int MYSTRING_MAXLENGTH = 4; const int MYSTRING_MAXLENGTH = 4; char mystring[MYSTRING_MAXLENGTH + 1]; char mystring[MYSTRING_MAXLENGTH + 1];
4242
Example: append 2Example: append 2ndnd to 1 to 1stst string string /**/**
Appends as much as possible from a string to another Appends as much as possible from a string to another stringstring
@param s the string to which t is appended @param s the string to which t is appended @param s_maxlength the maximum length of s (not @param s_maxlength the maximum length of s (not
counting '\0')counting '\0') @param t the string to append @param t the string to append
*/*/ void void appendappend(char s[], int s_maxlength, (char s[], int s_maxlength, constconst char t[]) { char t[]) {
int i = int i = strlenstrlen(s);(s); int j = 0; int j = 0; /* append t to s *//* append t to s */ whilewhile (t[j] != '\0' and i < s_maxlength) { (t[j] != '\0' and i < s_maxlength) {
Character ArraysCharacter Arrays Generally it is best to avoid the use of character Generally it is best to avoid the use of character
arrays - the string class is safer and far more arrays - the string class is safer and far more convenient. convenient.
Occasionally you need to convert a string into a Occasionally you need to convert a string into a character array to call a function that was written character array to call a function that was written before the string class was invented. before the string class was invented.
ExampleExample: to convert a character array containing : to convert a character array containing digits into its integer value. digits into its integer value.
int atoi(const char s[])int atoi(const char s[]) Use the c_str member function to convert a string Use the c_str member function to convert a string
into a character array. into a character array.
ExampleExample: : string year = "1999"; string year = "1999"; int y = atoi(year.c_str());int y = atoi(year.c_str());
4444
Two-Dimensional ArraysTwo-Dimensional Arrays It often happens that we want to store collections It often happens that we want to store collections
of numbers that have a two-dimensional layout.of numbers that have a two-dimensional layout. Such an arrangement, consisting of row and Such an arrangement, consisting of row and
columns of values, is called a columns of values, is called a two-dimensionaltwo-dimensional arrayarray, or a , or a matrixmatrix. .
C++ uses an array with two subscripts to store a C++ uses an array with two subscripts to store a two-dimensional array: two-dimensional array: ExampleExample: :
const int BALANCE_ROWS = 11; const int BALANCE_ROWS = 11; const int BALANCE_COLS = 6; const int BALANCE_COLS = 6; double balances[BALANCE_ROWS][BALANCE_COLS]; double balances[BALANCE_ROWS][BALANCE_COLS];
To select a particular element in the two-To select a particular element in the two-dimensional array, we need to specify two dimensional array, we need to specify two subscripts in separate brackets to select the row subscripts in separate brackets to select the row and column. and column.
4545
Accessing an Element in 2-dim arrayAccessing an Element in 2-dim array
Define a new variable that is a two-Define a new variable that is a two-dimensional array. dimensional array.
4747
Two-Dimensional ArraysTwo-Dimensional Arrays When passing a two-dimensional array to When passing a two-dimensional array to
a function, you must specify the number of a function, you must specify the number of columns columns as a constantas a constant with the parameter with the parameter type. type.
The number of rows can be variable.The number of rows can be variable. void print_table(const double table[][BALANCE_COLS], int table_rows) { void print_table(const double table[][BALANCE_COLS], int table_rows) {