+ All Categories

Vectors

Date post: 01-Jan-2016
Category:
Upload: leila-quinn
View: 18 times
Download: 0 times
Share this document with a friend
Description:
Vectors. One-Dimensional Containers. Problem. A file contains a sequence of names and scores: Ann92 Bob84 Chris89 ... Using OCD, design and implement a program that computes the average score, and displays each name, its score, and its difference from the average. - PowerPoint PPT Presentation
40
Vectors Vectors One-Dimensional Containers One-Dimensional Containers
Transcript
Page 1: Vectors

VectorsVectors

One-Dimensional ContainersOne-Dimensional Containers

Page 2: Vectors

ProblemProblem

A file contains a sequence of names and A file contains a sequence of names and scores:scores:AnnAnn 9292BobBob 8484ChrisChris 8989......

Using OCD, design and implement a program Using OCD, design and implement a program that computes the average score, and that computes the average score, and displays each name, its score, and its displays each name, its score, and its difference from the average.difference from the average.

Page 3: Vectors

Preliminary AnalysisPreliminary Analysis

This problem requires us to process the This problem requires us to process the scores twice:scores twice:

• Once to compute their average; andOnce to compute their average; and

• Once to compute the difference of each Once to compute the difference of each score from the average.score from the average.

Page 4: Vectors

Preliminary Analysis (Preliminary Analysis (Ct’dCt’d))

A good way is to use A good way is to use vectorsvectors, and, and

• store the sequence of names in one vector,store the sequence of names in one vector,

• store the sequence of scores in another store the sequence of scores in another vector.vector.

A vector is a container for storing sequences of A vector is a container for storing sequences of values of the same type.values of the same type.

By using two vectors, we can process the scores By using two vectors, we can process the scores twice without processing the names twice.twice without processing the names twice.

Page 5: Vectors

BehaviorBehavior

Our program should get the names of the Our program should get the names of the input and output files from the user, open input and output files from the user, open fstreams to those files, and verify that fstreams to those files, and verify that they opened. It should then read the they opened. It should then read the names into one vector and the scores into names into one vector and the scores into another vector. It should then compute another vector. It should then compute the average of the values in the scores the average of the values in the scores vector. It should then write to the output vector. It should then write to the output file each name, its corresponding score, file each name, its corresponding score, and the difference of that score and the and the difference of that score and the average.average.

Page 6: Vectors

ObjectsObjects

Description Type Kind NameDescription Type Kind Namein-file name string varying inFileName

input fstream ifstream varying fin

names vector<string> varying nameVecscores vector<double> varying scoreVecaverage double varying average

difference double varying --

out-file name string varying outFileName

output fstream ofstream varying fout

name string varying nameVec[i]score double varying scoreVec[i]

Page 7: Vectors

OperationsOperations

Description Predefined? Library? NameDescription Predefined? Library? Name

display a string yes string <<read a string yes string >>open/close file yes fstream -- streams

read names and no -- -- numbers into vectors

average a vector no -- --

display names, no -- -- scores & difference

Page 8: Vectors

AlgorithmAlgorithm0. Display purpose of 0. Display purpose of the the programprogram1. Prompt for and read name of input file from 1. Prompt for and read name of input file from cincin into into

inFileNameinFileName..2. Prompt for and read name of output file from cin into 2. Prompt for and read name of output file from cin into

outFileNameoutFileName..3. Open 3. Open finfin to to inFileNameinFileName, , foutfout to to outFileNameoutFileName, verify , verify

opens.opens.4. 4. Read names, scores from Read names, scores from finfin into into nameVecnameVec, ,

scoreVecscoreVec..5. Close 5. Close finfin..6. Compute 6. Compute averageaverage of scores in of scores in scoreVecscoreVec..7. Display 7. Display nameVecnameVec, , scoreVecscoreVec, and , and averageaverage differences differences

to to foutfout..8. Close fout.8. Close fout.9. Display a ‘processing completed’ message to 9. Display a ‘processing completed’ message to coutcout..

Page 9: Vectors

DiscussionDiscussion

Steps 4, 6 and 7 are not predefined, so Steps 4, 6 and 7 are not predefined, so we need to write functions to perform we need to write functions to perform them.them.

We will begin by writing the function to We will begin by writing the function to fill the two vectors with values from the fill the two vectors with values from the ifstream.ifstream.

Page 10: Vectors

Function 1 BehaviorFunction 1 Behavior

Our function should receive from its caller Our function should receive from its caller an ifstream, an (empty) vector of strings, an ifstream, an (empty) vector of strings, and an (empty) vector of doubles. Using and an (empty) vector of doubles. Using an input loop, the function should read a an input loop, the function should read a name and score, append the name to name and score, append the name to the vector of strings, and append the the vector of strings, and append the score to the vector of doubles. On exiting score to the vector of doubles. On exiting the loop, the function should pass the the loop, the function should pass the name-vector and score-vector back to name-vector and score-vector back to the caller.the caller.

Page 11: Vectors

Function 1 AlgorithmFunction 1 Algorithm0. Receive 0. Receive finfin, , nameVecnameVec, , scoreVecscoreVec from caller. from caller.1. Loop:1. Loop:

a. Read a. Read namename, , scorescore, from , from finfin..b. If end-of-file was reached, exit loop.b. If end-of-file was reached, exit loop.c. Append c. Append namename to to nameVecnameVec..d. Append d. Append scorescore to to scoreVecscoreVec..End loop.End loop.

Page 12: Vectors

Function 1 CodingFunction 1 Coding#include <fstream> // ifstream, eof(), ...#include <vector> // vectorusing namespace std;

void FillVectors(ifstream & fin, vector<string> & nameVec, vector<double> & scoreVec){ string name; // input variables double score;

for (;;) // Loop: { fin >> name >> score; // read name, score if (fin.eof()) break; // if none left, quit nameVec.push_back(name); // append name to nameVec scoreVec.push_back(score); // append score to scoreVec }}

Page 13: Vectors

Function 2 BehaviorFunction 2 Behavior

Our function should receive from its Our function should receive from its caller a vector of double values. If caller a vector of double values. If there are more than 0 values in the there are more than 0 values in the vector, it should compute their sum vector, it should compute their sum and return their average; otherwise, it and return their average; otherwise, it should display an error message and should display an error message and return 0 as a default value.return 0 as a default value.

Page 14: Vectors

Function 2 AlgorithmFunction 2 Algorithm0. Receive 0. Receive numberVecnumberVec from caller. from caller.1. Compute 1. Compute numValuesnumValues = = numberVec.size().numberVec.size().2. If 2. If numValuesnumValues > 0 values: > 0 values:

a. Compute a. Compute sumsum of values in of values in numberVecnumberVec..b. Return sum / numValues.b. Return sum / numValues.

ElseElsea. Display error message.a. Display error message.b. Return 0.0.b. Return 0.0.

End if.End if.

Page 15: Vectors

Function 2 CodingFunction 2 Coding#include <vector> // vector#include <numeric> // accumulate()using namespace std;

double Average(const vector<double> & numberVec){ int numValues = numberVec.size(); if (numValues > 0) { double sum = accumulate(numberVec.begin(), numberVec.end(), 0); return sum / numValues; } else { cerr << “\n*** Average: vector is empty!\n” << endl; return 0.0; }}

Page 16: Vectors

Function 2 DiscussionFunction 2 Discussion

The accumulate() function is a part of the The accumulate() function is a part of the C++ standard template library, and can C++ standard template library, and can be used to sum the values in any be used to sum the values in any container (e.g., vector) in the library.container (e.g., vector) in the library.

Pattern:Pattern:

sum = accumulate(vec.begin(), // start vec.end(), // stop 0); // initial

// value

Page 17: Vectors

Function 3 BehaviorFunction 3 Behavior

Our function should receive from its Our function should receive from its caller an ofstream, a vector of names, caller an ofstream, a vector of names, a vector of scores, and an average. a vector of scores, and an average. The function should use a loop to write The function should use a loop to write to the ofstream each name, its to the ofstream each name, its corresponding score, and its difference corresponding score, and its difference from the average.from the average.

Page 18: Vectors

Function 3 ObjectsFunction 3 Objects

Description Type Movement NameDescription Type Movement Name

ofstream ofstream in-out fout

average double in average

name-vec vector<string> in names

score-vec vector<double> in scores

difference double local scores[i]- average

Page 19: Vectors

Function 3 OperationsFunction 3 Operations

Description Predefined? Library? NameDescription Predefined? Library? Name

receive params yes built-in --determine size yes vector size() of a vector

select value of yes vector [] a vector

write string to yes string << ofstream

write double to yes fstream << ofstream

Page 20: Vectors

Function 3 AlgorithmFunction 3 Algorithm

0. Receive 0. Receive fout, names, scores, averagefout, names, scores, average from caller. from caller.1. For each index 1. For each index ii of of namesnames::

Write Write names[i]names[i], , scores[i]scores[i], and , and scores[i]-scores[i]-averageaverage to to foutfout..

Page 21: Vectors

Function 3 CodingFunction 3 Coding#include <vector> // vector#include <fstream> // ofstreamusing namespace std;

void WriteResults(ofstream & fout, const vector<string> & names, const vector<double> & scores, double average){ for (int i = 0; i < names.size(); i++) fout << names[i] << ‘\t’ << scores[i] << ‘\t’ << scores[i] - average << endl;}

Page 22: Vectors

CodingCoding/* processScores.cpp * ... */#include <iostream> // cin, cout, ...#include <fstream> // ifstream, ofstream, ...#include <string> // string#include <cassert> // assert()#include <vector> // vectorusing namespace std;

#include “MyVectorOps.h” // Average()

// local prototypesvoid FillVectors(ifstream & fin, vector<string> & nameVec, vector<double> & scoreVec)void WriteResults(ofstream & fout, const vector<string> & names, const vector<double> & scores, double average);

Page 23: Vectors

Coding (Coding (Ct’dCt’d))int main(){ cout << “\nTo process the names/scores in an input file,” << “\n enter the name of the file: “; string inFileName; cin >> inFileName;

cout << “\nEnter the name of the output file: ”; string outFileName; cin >> outFileName;

ifstream fin(inFileName.data()); // open streams ofstream fout(outFileName.data()); assert(fin.is_open() && fout.is_open()); // verify opens

vector<string> nameVec; vector<double> scoreVec;

Page 24: Vectors

Coding (Coding (Ct’dCt’d))

FillVectors(fin, nameVec, scoreVec); // input fin.close();

double average = Average(scoreVec); // process

WriteResults(fout, nameVec, scoreVec, average); // output fout.close();

cout << “\nProcessing complete. Results are in \’” << outFileName << “\’.\n” << endl;}

// ... definitions of FillVectors(), WriteResults() go here

//vec.cpp

Page 25: Vectors

TestingTesting

To test our program, we use a text editor To test our program, we use a text editor and create easy-to-check input files:and create easy-to-check input files:

Ann 90Bob 80Chris 70

If we name this particular file If we name this particular file test1.txttest1.txt, , then for it, our program should display:then for it, our program should display:Ann 90 10Bob 80 0Chris 70 -10

Page 26: Vectors

26

Vector AttributesVector Attributes

A vector has several attributes, including A vector has several attributes, including itsits

• datadata -- the values it contains. -- the values it contains.

• sizesize -- the number of values it contains; -- the number of values it contains; andand

• capacitycapacity -- the number of values it can -- the number of values it can store before having to grow.store before having to grow.13 21 08 14 19

0 1 2 3 4data

5

size

5

capacity

Page 27: Vectors

27

size() and capacity()size() and capacity()

From this, it should be obvious that the From this, it should be obvious that the vector function member vector function member size() simply simply returns the value of its size attribute:returns the value of its size attribute:

A vector also has a function member A vector also has a function member named named capacity() that returns the that returns the value of its capacity attribute.value of its capacity attribute.

13 21 08 14 19

0 1 2 3 4data

5

size

5

capacity

Page 28: Vectors

28

Declarations: 3 FormsDeclarations: 3 Forms vector<double> aVector; // empty

data

0

size

0

capacity

0 0 0 0 0

0 1 2 3 4data

8

size

8

capacity

0

5

0

6

0

7

const int N = 8; // N default vector<double> aVector(N); // values

1 1 1 1 1

0 1 2 3 4data

8

size

8

capacity

1

5

1

6

1

7

const int N = 8; // N specified vector<double> aVector(N, 1); // values

Page 29: Vectors

29

Vector DeclarationsVector Declarations

You can pass any type to a vector when it is declared:You can pass any type to a vector when it is declared:

0 0 0 0 0

0 1 2 3 4data

8

size

8

capacity

0

5

0

6

0

7

const int N = 8; vector<bool> boolVec(N, false);

Hi Hi Hi Hi Hi

0 1 2 3 4data

8

size

8

capacity

Hi

5

Hi

6

Hi

7

const int N = 8; vector<string> stringVec(N, “Hi”);

Page 30: Vectors

30

Vector push_back()Vector push_back()Values can be appended to a vector using the Values can be appended to a vector using the push_back() function member, which causes the function member, which causes the vector to “grow” if necessary.vector to “grow” if necessary.

aVec.push_back(13);

vector<double> aVec; // empty

data

0

size

0

capacity

13

0data

1

size

1

capacity

Page 31: Vectors

31

Appending (Appending (Ct’dCt’d))

Subsequent calls to Subsequent calls to push_back() continue to append: continue to append:

aVec.push_back(6); aVec.push_back(21);

13 6 21

0 1 2data

3

size

3

capacity

When the size equals the capacity, a call to When the size equals the capacity, a call to push_back() causes the vector to grow again.push_back() causes the vector to grow again.

The only limit on a vector’s growth is the amount The only limit on a vector’s growth is the amount of memory available.of memory available.

Page 32: Vectors

32

Vector pop_back()Vector pop_back()

To remove the most recently appended value, the vector function member To remove the most recently appended value, the vector function member pop_back() can be used: can be used:

aVec.pop_back();

13 6 21

0 1 2data

3

size

3

capacity

13 6

0 1data

2

size

3

capacity

Note that Note that push_back() and and pop_back() alter size. alter size.

2

Page 33: Vectors

33

Vector front() and back()Vector front() and back()The first and last values in a vector can be The first and last values in a vector can be

retrieved with the retrieved with the front() and and back() function function members:members:

13 6

0 1data

2

size

2

capacity

double alpha = aVec.front(); // alpha == 13

double omega = aVec.back(); // omega == 6

The The front() and and back() function members function members provide a convenient way to access the ends provide a convenient way to access the ends of a vector without finding using subscripts.of a vector without finding using subscripts.

Page 34: Vectors

34

Vector SubscriptVector SubscriptLike a string, the individual values in a vector can be Like a string, the individual values in a vector can be

accessed using the subscript ([]) operator.accessed using the subscript ([]) operator.

13 6

0 1data

2

size

2

capacity

double first = aVec[0]; // first == 13

double second = aVec[1]; // second == 6

The subscript operation The subscript operation aVec[i] provides a provides a convenient way to access the value in convenient way to access the value in aVec whose index is whose index is i, where , where i is a for loop control is a for loop control variable.variable.

Page 35: Vectors

35

Safe Vector Element Safe Vector Element AccessAccess

The subscript operator does not check that the The subscript operator does not check that the index being accessed is valid.index being accessed is valid.

The The at() function member does check the index function member does check the index for validity, making it safer, but slower.for validity, making it safer, but slower.

13 6

0 1data

2

size

2

capacity

double first = aVec.at(0); // first == 13

double second = aVec.at(1); // second == 6

Page 36: Vectors

36

Vector IteratorsVector Iterators

Each STL container provides 2 function members:Each STL container provides 2 function members:– begin(), that points to the first data value; and, that points to the first data value; and

– end(), that points beyond the last data value., that points beyond the last data value.

13 6 21

0 1 2 3 4data

3

size

8

capacity 5 6 7

aVec

aVec.begin() aVec.end()

STL uses such “pointers” to iterate through the STL uses such “pointers” to iterate through the values of a container, and so they are called values of a container, and so they are called iteratorsiterators..

Page 37: Vectors

37

STL AlgorithmsSTL Algorithms

In addition to containers like class vector, In addition to containers like class vector, the STL defines a rich set of the STL defines a rich set of algorithmsalgorithms that can be applied to any STL that can be applied to any STL container, just by using the directive: container, just by using the directive:

#include <numeric>

To make these algorithms independent of To make these algorithms independent of any particular container, they take as any particular container, they take as arguments a container’s iterators, arguments a container’s iterators, rather than the container itself.rather than the container itself.

Page 38: Vectors

38

Algorithm accumulate()Algorithm accumulate()The The accumulate() algorithm returns the result of algorithm returns the result of

applying + to each of an STL container’s values:applying + to each of an STL container’s values:

double sum = accumulate(aVec.begin(), // sum aVec.end(), 0); // == // 40

The third argument to The third argument to accumulate() lets you lets you sum starting with a base value other than sum starting with a base value other than zero.zero.

//vectest.cpp//vectest.cpp

13 6 21

0 1 2 3 4data

3

size

8

capacity 5 6 7

aVec

aVec.begin() aVec.end()

Page 39: Vectors

39

SummarySummary

C++ provides the C++ provides the vectorvector, an object for storing sequences , an object for storing sequences of values of the same type.of values of the same type.

Since it stores multiple values, a vector is a special kind Since it stores multiple values, a vector is a special kind of object called a of object called a containercontainer..

The standard template library provides several The standard template library provides several predefined container classes, along with operations to predefined container classes, along with operations to manipulate them.manipulate them.

Page 40: Vectors

40

SummarySummary

The vector class provides many function The vector class provides many function members for operating on vectors.members for operating on vectors.

The C++ standard template library (STL) The C++ standard template library (STL) provides provides containerscontainers, , algorithmsalgorithms, and , and iteratorsiterators to connect algorithms and to connect algorithms and containers.containers.

A vector is an STL container, so that many A vector is an STL container, so that many STL algorithms can be used to operate on STL algorithms can be used to operate on vectors.vectors.


Recommended