47
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

1 Chapter 9: Vectors and Arrays Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

Embed Size (px)

Citation preview

Page 1: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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

Page 2: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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:

32000 32000 54000 54000 67500 67500 29000 29000 35000 35000 80000 80000

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 …).

Page 3: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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.

Page 4: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

44

Using Vectors to Collect Data Items Using Vectors to Collect Data Items

(Syntax 9.1 Vector Variable Definition)(Syntax 9.1 Vector Variable Definition)

SyntaxSyntaxvector<vector<type_nametype_name>> variable_name variable_name vector<vector<type_nametype_name> > var_namevar_name((initial_sizeinitial_size); );

ExampleExample: :

vector<int> scores; vector<int> scores;

vector<Employee> staff(20); vector<Employee> staff(20);

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.

Page 5: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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.

ExampleExample: : cout << salaries[4] << "\n"; cout << salaries[4] << "\n";

Page 6: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

66

Using Vectors to Collect Data Items Using Vectors to Collect Data Items (cont.)(cont.)

In C++, the slots of In C++, the slots of vectors are vectors are numbered numbered starting starting at 0at 0. .

Page 7: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

77

Syntax 9.2 : Vector SubscriptsSyntax 9.2 : Vector Subscripts

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.

Page 8: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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

error.error.

Example:Example: vector<double> staff(10);vector<double> staff(10); cout << staff[10]; cout << staff[10];

/* 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;

Page 9: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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.

vector<double> salaries; vector<double> salaries; . . . . . . double s; double s; cin >> s; cin >> s; . . . . . . salaries.push_back(s);salaries.push_back(s);

Page 10: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

1010

Vector Subscripts (cont.)Vector Subscripts (cont.)

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.

Page 11: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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: }

Page 12: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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.

ExampleExample: : void raise_by_percent(vector<double>& v, double void raise_by_percent(vector<double>& v, double

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); } }

Page 13: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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;} }

Page 14: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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;} }

Page 15: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

1515

Vector Parameters and Return Vector Parameters and Return Values (matches.cpp)Values (matches.cpp)

25: int 25: int mainmain() {  () {   27:    vector<double>  27:    vector<double> salariessalaries(5);(5); 28:    salaries[0] = 35000.0; 28:    salaries[0] = 35000.0; 29:    salaries[1] = 63000.0; 29:    salaries[1] = 63000.0; 30:    salaries[2] = 48000.0; 30:    salaries[2] = 48000.0; 31:    salaries[3] = 78000.0; 31:    salaries[3] = 78000.0; 32:    salaries[4] = 51500.0; 32:    salaries[4] = 51500.0; 33:  33:  34:    vector<int> matches =  34:    vector<int> matches =

find_all_betweenfind_all_between(salaries, 45000.0, (salaries, 45000.0, 65000.0);65000.0);

 36:  36:  37:     37:    forfor (int j = 0; j < matches. (int j = 0; j < matches.sizesize(); j++)(); j++) 38:       cout << salaries[matches[j]] << "\n"; 38:       cout << salaries[matches[j]] << "\n"; 39:     39:    returnreturn 0; 0; 40: } 40: }   

Page 16: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

1616

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();}}

Page 17: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

17

Example of Element Removal

Page 18: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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();} }

Page 19: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

19

Removing and Inserting Elements

Page 20: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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;

} }

Page 21: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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.

Page 22: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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).

ACMA P600 Price: 995 Score75 ACMA P600 Price: 995 Score75

ALaris Nx686 Price 798 Score 57 ALaris Nx686 Price 798 Score 57

AMAX Powerstation 600 Price: 999 Score 75AMAX Powerstation 600 Price: 999 Score 75

AMS Infogold P600 Price: 795 Score: 69 AMS Infogold P600 Price: 795 Score: 69

AST PRemmia Price: 2080 Score: 80 AST PRemmia Price: 2080 Score: 80

Austin 600 Price: 1499 Score: 95 Austin 600 Price: 1499 Score: 95

best value => Blackship NX-600 Price 598 Score: 60best value => Blackship NX-600 Price 598 Score: 60

Kompac 690 Price: 695 Score: 60 Kompac 690 Price: 695 Score: 60

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.

Page 23: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

23

Parallel Vectors (cont.)

• Each slice - names[i], prices[i], scores[i] - contains data that needs to be processed together.

Page 24: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

2424

Parallel Vectors (bestval1.cpp) Parallel Vectors (bestval1.cpp)

  01: 01: #include#include <iostream> <iostream> 02: 02: #include#include <string> <string> 03: 03: #include#include <vector> <vector> 04:  04: 05: 05: usingusing namespacenamespace std; std; 06: 06: 07: int 07: int mainmain() {  () {   09:    vector<string> names; 09:    vector<string> names; 10:    vector<double> prices; 10:    vector<double> prices; 11:    vector<int> scores; 11:    vector<int> scores; 12:  12:  13:    double best_price = 1; 13:    double best_price = 1; 14:    int best_score = 0; 14:    int best_score = 0; 15:    int best_index = -1; 15:    int best_index = -1; 16:  16:  17:    bool more =  17:    bool more = truetrue;; 47: 47:

Page 25: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

2525

bestval1.cpp (cont.)bestval1.cpp (cont.)  18:    18:    whilewhile (more) {  (more) {   20:       string next_name;20:       string next_name; 21:       cout << "Please enter the model name: ";21:       cout << "Please enter the model name: "; 22:       22:       getlinegetline(cin, next_name); 23:       names.(cin, next_name); 23:       names.push_backpush_back(next_name);(next_name); 24:       double next_price;24:       double next_price; 25:       cout << "Please enter the price: ";25:       cout << "Please enter the price: "; 26:       cin >> next_price;26:       cin >> next_price; 27:       prices.27:       prices.push_backpush_back(next_price);(next_price); 28:       int next_score;28:       int next_score; 29:       cout << "Please enter the score: ";29:       cout << "Please enter the score: "; 30:       cin >> next_score;30:       cin >> next_score; 31:       scores.31:       scores.push_backpush_back(next_score);(next_score); 32:       string remainder; 32:       string remainder; /* read remainder of line *//* read remainder of line */ 33:       33:       getlinegetline(cin, remainder); (cin, remainder); 34: 34: 35:       35:       ifif (next_score / next_price > best_score / best_price) {  (next_score / next_price > best_score / best_price) {    37:          best_index = names.37:          best_index = names.sizesize() - 1;() - 1;  38:          best_score = next_score;38:          best_score = next_score;  39:          best_price = next_price;39:          best_price = next_price;  40:       }     40:       }       41: 41:   42:       cout << "More data? (y/n) ";42:       cout << "More data? (y/n) ";  43:       string answer;43:       string answer;  44:       44:       getlinegetline(cin, answer);(cin, answer);  45:       45:       ifif (answer != "y") more = (answer != "y") more = falsefalse;;  46:    }46:    }

Page 26: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

2626

bestval1.cpp (cont.)bestval1.cpp (cont.)

48:    48:    forfor (int i = 0; i < names. (int i = 0; i < names.sizesize(); i++) { (); i++) { 50:       50:       ifif (i == best_index) (i == best_index)

cout << "best value => ";cout << "best value => ";51:       cout << names[i]51:       cout << names[i]52:          << " Price: " << prices[i]52:          << " Price: " << prices[i]53:          << " Score: " << scores[i] << "\n";53:          << " Score: " << scores[i] << "\n";54:    }54:    }55: 55: 56:    56:    returnreturn 0; 0;57: }57: }

  

Page 27: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

2727

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.

Page 28: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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.

Page 29: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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: };

Page 30: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

3030

Class Class Product Product (cont.)(cont.) 042: Product::042: Product::ProductProduct()() 043: {   043: {   044:    price = 0; 044:    price = 0; 045:    score = 0; 045:    score = 0; 046: } 046: } 047:  047:  048: void Product:: 048: void Product::readread() {  () {   050:    cout << "Please enter the model name: "; 050:    cout << "Please enter the model name: "; 051:     051:    getlinegetline(cin, name);(cin, name); 052:    cout << "Please enter the price: "; 052:    cout << "Please enter the price: "; 053:    cin >> price; 053:    cin >> price; 054:    cout << "Please enter the score: "; 054:    cout << "Please enter the score: "; 055:    cin >> score; 055:    cin >> score; 056:    string remainder;  056:    string remainder; /* read remainder of line *//* read remainder of line */ 057:     057:    getlinegetline(cin, remainder);(cin, remainder); 058: } 058: } 059:  059:  060: bool Product:: 060: bool Product::is_better_thanis_better_than(Product b) (Product b) const const {  {   062:     062:    ifif (price == 0) (price == 0) returnreturn falsefalse;; 063:     063:    ifif (b.price == 0) (b.price == 0) returnreturn truetrue;; 064:     064:    returnreturn score / price > b.score / b.price; score / price > b.score / b.price; 065: } 065: } 066:  066:  067: void Product:: 067: void Product::printprint() () const const {  {   069:    cout << name 069:    cout << name 070:       << " Price: " << price 070:       << " Price: " << price 071:       << " Score: " << score << "\n"; 071:       << " Score: " << score << "\n"; 072: } 072: } 073:  073:

Page 31: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

3131

New Version of bestval.cppNew Version of bestval.cpp 074: int 074: int mainmain() {  () { 

 076:    vector<Product> products; 076:    vector<Product> products; 077:  077:  078:    Product best_product; 078:    Product best_product; 079:    int best_index = -1; 079:    int best_index = -1; 080:  080:  081:    bool more =  081:    bool more = truetrue;; 082:     082:    whilewhile (more)  {  (more)  {   084:       Product next_product; 084:       Product next_product; 085:       next_product. 085:       next_product.readread();(); 086:       products. 086:       products.push_backpush_back(next_product);(next_product); 087:  087:  088:        088:       ifif (next_product. (next_product.is_better_thanis_better_than(best_product))(best_product)) 089:       {   089:       {   090:          best_index = products. 090:          best_index = products.sizesize() - 1;() - 1; 091:          best_product = next_product; 091:          best_product = next_product; 092:       }      092:       }      093:  093:  094:       cout << "More data? (y/n) "; 094:       cout << "More data? (y/n) "; 095:       string answer; 095:       string answer; 096:        096:       getlinegetline(cin, answer);(cin, answer); 097:        097:       ifif (answer != "y") more = (answer != "y") more = falsefalse;; 098:    } 098:    } 099:  099:  100:     100:    forfor (int i = 0; i < products. (int i = 0; i < products.sizesize(); i++)  {(); i++)  { 102:        102:       ifif (i == best_index) cout << "best value => "; (i == best_index) cout << "best value => "; 103:       products[i]. 103:       products[i].printprint();(); 104:    } 104:    } 105:  105:  106:     106:    returnreturn 0; 0; 107: }  107: }

Page 32: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

3232

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.

Page 33: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

3333

ArraysArrays Declaring an array is very similar to declaring a Declaring an array is very similar to declaring a

vector. vector. • Array declaration : Array declaration : double salaries[10]; double salaries[10]; • Vector declaration : Vector declaration : vector<double> salaries(10); vector<double> salaries(10);

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];

Page 34: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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++;    }    } }  }

Page 35: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

3535

Arrays (Syntax 9.3: Array Variable Definition)Arrays (Syntax 9.3: Array Variable Definition)

Array Variable DefinitionArray Variable Definition

type_name variable_nametype_name variable_name[[sizesize]];;

ExampleExample: :

int scores[20]; int scores[20];

PurposePurpose: :

Define a new variable of an arrayDefine a new variable of an array

type.type.

Page 36: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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)

Page 37: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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,

int& a_size) {int& a_size) { a_size = 0; a_size = 0; while (a_size < a_capacity) { while (a_size < a_capacity) {

double x; double x; cin >> x; cin >> x; if (cin.fail()) return; if (cin.fail()) return; a[a_size] = x; a[a_size] = x;

a_size++; a_size++; } }

} }

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.

Page 38: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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) {

a_size = 0;a_size = 0; double x;double x; whilewhile (a_size < a_capacity && (cin >> x)) { (a_size < a_capacity && (cin >> x)) {

a[a_size] = x;a[a_size] = x;a_size++;a_size++;

}} }}

It assumes the number of values read is <= capacity…It assumes the number of values read is <= capacity…

Page 39: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

3939

Example: max value in an arrayExample: max value in an array/**/**     Computes the maximum value in an arrayComputes the maximum value in an array

@param a the array@param a the array@param a_size the number of values in a@param a_size the number of values in a

*/*/                          double double maximummaximum((constconst double a[], int a_size) {  double a[], int a_size) {       ifif (a_size == 0) (a_size == 0) returnreturn 0; 0;

        double highest = a[0];double highest = a[0];

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;

}}   

Page 40: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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. .

g[0] g[1] g[2] g[3] g[4] g[5]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 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’

Page 41: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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];

Page 42: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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) { 

s[i] = t[j];s[i] = t[j];            i++;i++;       j++;       j++;     }     }            /* add zero terminator *//* add zero terminator */      s[i] = '\0';      s[i] = '\0';

}}   

Page 43: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

4343

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());

Page 44: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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.

Page 45: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

4545

Accessing an Element in 2-dim arrayAccessing an Element in 2-dim array

Page 46: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

4646

Two-Dimensional Array DefinitionTwo-Dimensional Array Definition

Syntax Two-Dimensional Array DefinitionSyntax Two-Dimensional Array Definition

type_name variable_nametype_name variable_name[[sizesize1][1][sizesize2];2];

ExampleExample: :

double monthly_sales[NREGIONS][12];double monthly_sales[NREGIONS][12]; PurposePurpose: :

Define a new variable that is a two-Define a new variable that is a two-dimensional array. dimensional array.

Page 47: 1 Chapter 9: Vectors and Arrays  Chapter Goals To become familiar with using vectors to collect objectsTo become familiar with using vectors to collect

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) {

const int WIDTH = 10; const int WIDTH = 10;

cout << fixed << setprecision(2); cout << fixed << setprecision(2);

for (int i = 0; i < table_rows; i++) { for (int i = 0; i < table_rows; i++) {

for (int j = 0; j < BALANCES_COLS; j++) for (int j = 0; j < BALANCES_COLS; j++)

cout << setw(WIDTH) << table[i][j]; cout << setw(WIDTH) << table[i][j];

cout << "\n"; cout << "\n";

} }

} }