SlideShare uma empresa Scribd logo
1 de 35
Baixar para ler offline
Arrays and Vectors
Sequential (One-Dimensional) Containers
Chapter 12
1
Problem
A file contains a sequence of names and scores:
Ann 92
Bob 84
Chris 89
. . .
Write a program that computes the average score,
and displays each name, its score, and its difference
from the average.
2
Lab 10: average, standard
deviation, grade on the curve
Proj 10: median also
Note the different
types of data
Preliminary Analysis
This problem requires us to process the scores
twice:
Once to compute their average; and
Once to compute the difference of each score
from the average.
One way is to close the file, then reopen it with
open() [or use seekg() to begin reading from the
beginning of the file]. But that would force us to read
each name twice, which is unnecessary; it is also
inefficient because disk I/O is considerably slower
than transferring data from internal memory.
3
Lab 10: 3 times
Proj 10: Many times
p. 478
A better way is to use
containers in main memory
and store the:
sequence of names in one
container
sequence of scores in another
container.
4
Ann
Bob
Chris
•
•
•
92
84
89
•
•
•
names
scores
Ann 92
Bob 84
Chris 89
...
disk
file
memory
By using two such containers, we
can process the scores twice without
processing the names twice and
without having to read the values
from disk more than once.
Valarrays
Vectors
5
Sequential Containers
C++ provides several in-memory containers for
storing and processing sequences of values of the
same type. The candidates here are:
Arrays (from C)
Other containers studied in data structures courses:
• stacks
• queues
• priority queues
. . . and more . . .
•linked lists
•binary search trees
•directed graphs
One of the containers in STL
(Standard Template Library)
www.sgi.com/tech/stl
C (and C++) provide two types of arrays:
• Static: Memory allocation is specified at compile-time
(This is the only kind we'll study — see §12.2)
• Dynamic: Memory is allocated during run-time
An array declaration (static) has the form:
element_type name[constant_capacity];
Example:
double x[50];
This allocates a block of 50 consecutive memory
locations for storing doubles and associates the name x
with it. They are numbered 0, 1, . . ., 49.
6
C-Style Arrays
Two-dimensional array
(matrix)?
double y[10][50];
# rows # columns
0 1 3 . . . 49
x
2
. . .
7
Because it may be necessary to change the capacity of
the array to store more/fewer data items, it is better to
not "hard-wire" the capacity into the declaration;
instead, use a named constant:
const int CAPACITY = 50;
. . .
double x[CAPACITY];
To change the capacity, we need only change the
const declaration.
Extra: An example of how to create a dynamic array
double * x;
// x is a pointer to (address of) a memory
// location where a double can be stored
int cap;
cout << "Enter array's capacity: ";
cin >> cap;
x = new double[cap]; // allocate memory block for x
8
Example: Read and store up to 50 doubles in x.
cout << "# of values (<= " << CAPACITY << ")?";
cin >> numVals;
for (int i = 0; i < numVals; i++)
cin >> x[i];
For either kind of array, data values can now be
stored in the array elements. They are accessed by
using the subscript operator. The names of the
individual elements are:
x[0], x[1], x[2], . . .
In general, x[i] is the i-th location in the array x;
i is called an index or subscript.
88.0 92.5 78.5 99.0
0 1 3 . . . 49
2
x
C++ provides some other sequential containers that
remove some of the weaknesses of C-style arrays:
9
Valarrays (for mathematical vectors)
• Have predefined operations, but still fixed capacity
• Only numeric type
Vectors
• Have predefined operations
• Can grow when necessary (but not shrink)
• Elements can be of any type
See §12.6
So, we'll use vectors . . .
Fig. 12.2
Back to our Program
10
1. Get the name of the input file from the user.
2. From the input file, read names into one
vector and scores into another vector.
3. Compute the average of the values
in the scores vector.
4. Finally, output each name, its
corresponding score, and the
difference of that score and
the average.
Ann
Bob
Chris
•
•
•
92
84
89
•
•
•
names
scores
memory
Implementation in C++
1. We know how to use a string variable to store the name
of a file and use .data() to extract the name from it.
Or we could use: char inFileName[30];
cin >> inFileName;
ifstream fin(inFileName);
11
2. A declaration of a vector in C++ has the form:
vector<T> vec;
where T is the type of the elements of the vector vec.
vector is really a class template (like complex<T>). It
becomes a class when we specify what type T is.
12
So we need two vectors:
•vector of strings to store the names:
vector<string> nameVec;
•vector of doubles to store the scores:
vector<double> scoreVec;
Now we need to:
• fill these vectors from the file of names and scores
• compute the average of the scores in scoreVec
• output the names in nameVec, the scores in scoreVec, and the
differences between the scores and the average.
Since none of these operations are built into C++, we will write
functions to perform them.
Function #1: fillVectors()
This function should receive from its caller the
name of the input file, an (empty) vector of
strings, and an (empty) vector of doubles. It
should open an ifstream to the file. Then,
using an input loop, the function should read a
name and score, append the name to the vector
of strings, and append the score to the vector
of doubles. On exiting the loop, the
function should pass the name-vector
and score-vector back to the caller.
13
as in
Slide #4
• It must pass back two vectors, so these must be
reference parameters.
• It must repeatedly read a name and a score and
then append the name to the vector of names,
and the score to the vector of scores. The
vector class template provides a built-in
operation for this:
vecName.push_back(value);
14
See "C++ vector Library Quick
Reference" link on
CS 104 Other Course
Information page. Also, §12.6.
Observations about fillVectors()
//-- Needs <ifstream>, <cassert>, and <vector> libraries
void fillVectors(string inFileName,
vector<string> & nameVec,
vector<double> & scoreVec)
{
// open input stream to inFileName
ifstream fin(inFileName.data());
assert(fin.is_open());
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
}
fin.close();
}
15
Definition of fillVectors()
16
Function #2: average()
This function should receive from its caller a
vector of doubles. It must then compute the
average of these doubles, and return this
average.
• To avoid having to copy this (potentially large) vector,
we make it a constant reference parameter instead of a
value parameter.
• To compute the average score, we need to know how
many scores there are; vector has a built-in function
member for this:
vecName.size();
• We need the sum of the scores in scoreVec. Like
arrays, vectors have a subscript operator [ ], so we
could just use a for-loop for this:
double sum = 0;
for (int i = 0; i < scoreVec.size(); i++)
sum += scoreVec[i];
However, C++ has a function that does this. 17
Observations about average()
The accumulate() function can be used to sum the
values in a C++ container — vector, in particular.
It is found in the <numeric> library (possibly in
<algorithm> in older versions of C++).
Pattern:
18
sum = accumulate(vec.begin(), // start
vec.end(), // stop
0.0); // initial
// value
iterators:
begin() points to first element,
end() points just past last element,
Initial value of
sum; it also
determines the
type of the sum
(int or double)
See "C++ algorithm
Library Quick Reference"
link on CS 104 Other
Course Information
page. Also, §12.7.
// Needs <vector> and <numeric> libraries
double average( vector<double> numberVec)
{
int numValues = numberVec.size();
if (numValues > 0)
{
double sum =
return sum / numValues;
}
else
{
cerr << "n*** Average: vector is empty!n" << endl;
return 0.0;
}
}
19
accumulate(numberVec.begin(),
numberVec.end(), 0.0);
Definition of average()
Note: On the assignment, you will be building a useful library
named DoubleVectorOps that contains this function average()
along with functions for computing standard deviation and median.
const &
20
Function #3: displayResults()
This function should receive from its caller a
vector of names, a vector of scores, and an
average. It should then use a loop to output
each name, its corresponding score, and the
difference of the score from the average.
• Because it returns no value, like function #1, this will be
a void function that receives the two vectors — the
names and the scores — and the average score.
• Again, to avoid having to copy potentially large vectors,
we make them constant reference parameters instead of
value parameters.
• We can use a for-loop to run through the two vectors
and output each name, the corresponding score, and
the difference between that score and the average,
using the subscript operator [ ] to access the
individual names and scores (see slide #17).
21
Observations about displayResults()
22
Definition of displayResults()
// Needs <vector> library
void displayResults(const vector<string> & names,
const vector<double> & scores,
double theAverage)
{
for (int i = 0; i < names.size(); i++)
cout << names[i] << 't'
<< scores[i] << 't'
<< scores[i] - theAverage << endl;
}
Discussion
Now that all of the operations required by our
main function's algorithm exist, we are ready to
implement it.
23
Main Function Coding
/* processScores.cpp
...
----------------------*/
#include <iostream> // cin, cout, ...
#include <fstream> // ifstream, ...
#include <string> // string
#include <cassert> // assert()
#include <vector> // vector
#include <numeric> // accumulate()
using namespace std;
// local prototypes
void fillVectors(string inFileName,
vector<string> & nameVec,
vector<double> & scoreVec);
double average(const vector<double> & numberVec);
void displayResults(const vector<string> & names,
const vector<double> & scores,
double theAverage);
24
int main()
{
cout << "nTo process the names and scores in an input file,"
<< "n enter the name of the file: ";
string inFileName;
getline(cin, inFileName);
vector<string> nameVec;
vector<double> scoreVec;
fillVectors(inFileName, nameVec, scoreVec); // input
double theAverage = average(scoreVec); // process
displayResults(nameVec, scoreVec, theAverage ); // output
}
// Definitions of fillVectors(), average(), displayResults() go here
25
Testing
To test our program, we use a text editor and
create easy-to-check input files:
Ann 90
Bob 70
Chris 80
If we name this particular file test1.txt, then
for it, our program should display:
Ann 90 10
Bob 70 -10
Chris 80 0
26
Some Other Useful & Powerful Functions
You should explore the standard C++ libraries
<algorithm> and <numeric> to see some of
the functions you can “plug into” your programs
and save yourself hours of coding and testing if
you had to write them yourself.
Also, these powerful functions use the most
efficient methods known for carrying out
operations.
And they have been thoroughly tested so they can
be used with confidence.
27
One that you will learn about in the assignment is
the sort() function in the <algorithm> library.
It uses one of the fastest, if not the fastest, sorting
methods.
And like the other library functions, it is very easy
to use because they use iterators in much the same
way as the accumulate() function. For example,
to sort the scores in our example, we need only write:
sort(scoreVec , scoreVec );
28
.begin() .end()
Figure 12.2 Out-of-Range Errors.
/* Program to demonstrate aberrant behavior
resulting from out-of-range errors.
----------------------------------------------------*/
#include <iostream> // cout, <<
#include <iomanip> // setw()
using namespace std;
const int CAPACITY = 4;
typedef int IntArray[CAPACITY];
void printArray(char name, IntArray x, int numElements);
int main()
{
IntArray a = {0, 1, 2, 3},
b = {4, 5, 6, 7},
c = {8, 9, 10, 11};
int below = -3,
above = 6;
printArray('a', a, 4);
printArray('b', b, 4);
printArray('c', c, 4);
b[below] = -999;
b[above] = 999;
cout << endl;
printArray('a', a, 4);
printArray('b', b, 4);
printArray('c', c, 4);
}
/* printArray() displays an int array.
Receives: name, a character, and x, an int array
Output: name of array, and 4 values stored in it
--------------------------------------------------------*/
void printArray(char name, IntArray x, int numElements)
{
cout << name << " = ";
for (int i = 0; i < numElements; i++)
cout << setw(5) << x[i];
cout << endl;
}
Sample run:
a = 0 1 2 3
b = 4 5 6 7
c = 8 9 10 11
a = 0 1 999 3
b = 4 5 6 7
c = 8 -999 10 11
Algorithm for average():
1.Receive numVec.
2.Compute sum, the sum of the values in numVec.
3.Compute numValues, the number of values in numVec.
4.If numValues > 0:
Return sum / numValues.
Otherwise
1.Display an error message via cerr.
2.Return 0.0 as a default value.
5.End if.
Algorithm for fillVectors():
1.Receive inFileName, nameVec and scoreVec.
2.Open inStream, a stream to inFileName, and check that it opened successfully.
3.Loop
1.Read name and score from inStream.
2.If end-of-file was reached, terminate repetition.
3.Append name to nameVec.
4.Append score to scoreVec.
4.End loop.
5.Close inStream.
Main Function Coding
/* processScores.cpp
...
----------------------*/
#include <iostream> // cin, cout, ...
#include <fstream> // ifstream, ...
#include <string> // string
#include <cassert> // assert()
#include <vector> // vector
#include <numeric> // accumulate()
using namespace std;
// local prototypes
void fillVectors(string inFileName,
vector<string> & nameVec,
vector<double> & scoreVec);
double average(const vector<double> & numberVec);
void displayResults(const vector<string> & names,
const vector<double> & scores,
double theAverage);
31
int main()
{
cout << "nTo process the names and scores in an input file,"
<< "n enter the name of the file: ";
string inFileName;
getline(cin, inFileName);
vector<string> nameVec;
vector<double> scoreVec;
fillVectors(inFileName, nameVec, scoreVec); // input
double theAverage = average(scoreVec); // process
displayResults(nameVec, scoreVec, theAverage ); // output
}
// Definitions of fillVectors(), average(), displayResults() go here
32
//-- Needs <ifstream>, <cassert>, and <vector> libraries
void fillVectors(string inFileName,
vector<string> & nameVec,
vector<double> & scoreVec)
{
// open input stream to inFileName
ifstream fin(inFileName.data());
assert(fin.is_open());
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
}
fin.close();
}
33
Definition of fillVectors()
// Needs <vector> and <numeric> libraries
double average( vector<double> numberVec)
{
int numValues = numberVec.size();
if (numValues > 0)
{
double sum =
return sum / numValues;
}
else
{
cerr << "n*** Average: vector is empty!n" << endl;
return 0.0;
}
}
34
accumulate(numberVec.begin(),
numberVec.end(), 0.0);
Definition of average()
const &
35
Definition of displayResults()
// Needs <vector> library
void displayResults(const vector<string> & names,
const vector<double> & scores,
double theAverage)
{
for (int i = 0; i < names.size(); i++)
cout << names[i] << 't'
<< scores[i] << 't'
<< scores[i] - theAverage << endl;
}

Mais conteúdo relacionado

Semelhante a Vectors Intro.ppt

18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operatorSAFFI Ud Din Ahmad
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structurelodhran-hayat
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptxRockyIslam5
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysBlue Elephant Consulting
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1stConnex
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfLadallaRajKumar
 
C programming day#3.
C programming day#3.C programming day#3.
C programming day#3.Mohamed Fawzy
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 developmentFisnik Doko
 
CUDA by Example : Thread Cooperation : Notes
CUDA by Example : Thread Cooperation : NotesCUDA by Example : Thread Cooperation : Notes
CUDA by Example : Thread Cooperation : NotesSubhajit Sahu
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plusSayed Ahmed
 

Semelhante a Vectors Intro.ppt (20)

18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
Python - Lecture 12
Python - Lecture 12Python - Lecture 12
Python - Lecture 12
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
C++ Boot Camp Part 2
C++ Boot Camp Part 2C++ Boot Camp Part 2
C++ Boot Camp Part 2
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
C programming day#3.
C programming day#3.C programming day#3.
C programming day#3.
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
CUDA by Example : Thread Cooperation : Notes
CUDA by Example : Thread Cooperation : NotesCUDA by Example : Thread Cooperation : Notes
CUDA by Example : Thread Cooperation : Notes
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 

Último

TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHSneha Padhiar
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Romil Mishra
 
Module-1-Building Acoustics(Introduction)(Unit-1).pdf
Module-1-Building Acoustics(Introduction)(Unit-1).pdfModule-1-Building Acoustics(Introduction)(Unit-1).pdf
Module-1-Building Acoustics(Introduction)(Unit-1).pdfManish Kumar
 
Artificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewArtificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewsandhya757531
 
priority interrupt computer organization
priority interrupt computer organizationpriority interrupt computer organization
priority interrupt computer organizationchnrketan
 
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTFUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTSneha Padhiar
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communicationpanditadesh123
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Coursebim.edu.pl
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxRomil Mishra
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionSneha Padhiar
 
70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical trainingGladiatorsKasper
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptxmohitesoham12
 
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...Amil baba
 
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxCurve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxRomil Mishra
 
tourism-management-srs_compress-software-engineering.pdf
tourism-management-srs_compress-software-engineering.pdftourism-management-srs_compress-software-engineering.pdf
tourism-management-srs_compress-software-engineering.pdfchess188chess188
 
22CYT12 & Chemistry for Computer Systems_Unit-II-Corrosion & its Control Meth...
22CYT12 & Chemistry for Computer Systems_Unit-II-Corrosion & its Control Meth...22CYT12 & Chemistry for Computer Systems_Unit-II-Corrosion & its Control Meth...
22CYT12 & Chemistry for Computer Systems_Unit-II-Corrosion & its Control Meth...KrishnaveniKrishnara1
 
Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Communityprachaibot
 
Secure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech LabsSecure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech Labsamber724300
 
Javier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptxJavier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptxJavier Fernández Muñoz
 
The Satellite applications in telecommunication
The Satellite applications in telecommunicationThe Satellite applications in telecommunication
The Satellite applications in telecommunicationnovrain7111
 

Último (20)

TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________
 
Module-1-Building Acoustics(Introduction)(Unit-1).pdf
Module-1-Building Acoustics(Introduction)(Unit-1).pdfModule-1-Building Acoustics(Introduction)(Unit-1).pdf
Module-1-Building Acoustics(Introduction)(Unit-1).pdf
 
Artificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewArtificial Intelligence in Power System overview
Artificial Intelligence in Power System overview
 
priority interrupt computer organization
priority interrupt computer organizationpriority interrupt computer organization
priority interrupt computer organization
 
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTFUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communication
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Course
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based question
 
70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...
 
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxCurve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
 
tourism-management-srs_compress-software-engineering.pdf
tourism-management-srs_compress-software-engineering.pdftourism-management-srs_compress-software-engineering.pdf
tourism-management-srs_compress-software-engineering.pdf
 
22CYT12 & Chemistry for Computer Systems_Unit-II-Corrosion & its Control Meth...
22CYT12 & Chemistry for Computer Systems_Unit-II-Corrosion & its Control Meth...22CYT12 & Chemistry for Computer Systems_Unit-II-Corrosion & its Control Meth...
22CYT12 & Chemistry for Computer Systems_Unit-II-Corrosion & its Control Meth...
 
Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Community
 
Secure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech LabsSecure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech Labs
 
Javier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptxJavier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptx
 
The Satellite applications in telecommunication
The Satellite applications in telecommunicationThe Satellite applications in telecommunication
The Satellite applications in telecommunication
 

Vectors Intro.ppt

  • 1. Arrays and Vectors Sequential (One-Dimensional) Containers Chapter 12 1
  • 2. Problem A file contains a sequence of names and scores: Ann 92 Bob 84 Chris 89 . . . Write a program that computes the average score, and displays each name, its score, and its difference from the average. 2 Lab 10: average, standard deviation, grade on the curve Proj 10: median also Note the different types of data
  • 3. Preliminary Analysis This problem requires us to process the scores twice: Once to compute their average; and Once to compute the difference of each score from the average. One way is to close the file, then reopen it with open() [or use seekg() to begin reading from the beginning of the file]. But that would force us to read each name twice, which is unnecessary; it is also inefficient because disk I/O is considerably slower than transferring data from internal memory. 3 Lab 10: 3 times Proj 10: Many times p. 478
  • 4. A better way is to use containers in main memory and store the: sequence of names in one container sequence of scores in another container. 4 Ann Bob Chris • • • 92 84 89 • • • names scores Ann 92 Bob 84 Chris 89 ... disk file memory By using two such containers, we can process the scores twice without processing the names twice and without having to read the values from disk more than once.
  • 5. Valarrays Vectors 5 Sequential Containers C++ provides several in-memory containers for storing and processing sequences of values of the same type. The candidates here are: Arrays (from C) Other containers studied in data structures courses: • stacks • queues • priority queues . . . and more . . . •linked lists •binary search trees •directed graphs One of the containers in STL (Standard Template Library) www.sgi.com/tech/stl
  • 6. C (and C++) provide two types of arrays: • Static: Memory allocation is specified at compile-time (This is the only kind we'll study — see §12.2) • Dynamic: Memory is allocated during run-time An array declaration (static) has the form: element_type name[constant_capacity]; Example: double x[50]; This allocates a block of 50 consecutive memory locations for storing doubles and associates the name x with it. They are numbered 0, 1, . . ., 49. 6 C-Style Arrays Two-dimensional array (matrix)? double y[10][50]; # rows # columns 0 1 3 . . . 49 x 2 . . .
  • 7. 7 Because it may be necessary to change the capacity of the array to store more/fewer data items, it is better to not "hard-wire" the capacity into the declaration; instead, use a named constant: const int CAPACITY = 50; . . . double x[CAPACITY]; To change the capacity, we need only change the const declaration. Extra: An example of how to create a dynamic array double * x; // x is a pointer to (address of) a memory // location where a double can be stored int cap; cout << "Enter array's capacity: "; cin >> cap; x = new double[cap]; // allocate memory block for x
  • 8. 8 Example: Read and store up to 50 doubles in x. cout << "# of values (<= " << CAPACITY << ")?"; cin >> numVals; for (int i = 0; i < numVals; i++) cin >> x[i]; For either kind of array, data values can now be stored in the array elements. They are accessed by using the subscript operator. The names of the individual elements are: x[0], x[1], x[2], . . . In general, x[i] is the i-th location in the array x; i is called an index or subscript. 88.0 92.5 78.5 99.0 0 1 3 . . . 49 2 x
  • 9. C++ provides some other sequential containers that remove some of the weaknesses of C-style arrays: 9 Valarrays (for mathematical vectors) • Have predefined operations, but still fixed capacity • Only numeric type Vectors • Have predefined operations • Can grow when necessary (but not shrink) • Elements can be of any type See §12.6 So, we'll use vectors . . . Fig. 12.2
  • 10. Back to our Program 10 1. Get the name of the input file from the user. 2. From the input file, read names into one vector and scores into another vector. 3. Compute the average of the values in the scores vector. 4. Finally, output each name, its corresponding score, and the difference of that score and the average. Ann Bob Chris • • • 92 84 89 • • • names scores memory
  • 11. Implementation in C++ 1. We know how to use a string variable to store the name of a file and use .data() to extract the name from it. Or we could use: char inFileName[30]; cin >> inFileName; ifstream fin(inFileName); 11 2. A declaration of a vector in C++ has the form: vector<T> vec; where T is the type of the elements of the vector vec. vector is really a class template (like complex<T>). It becomes a class when we specify what type T is.
  • 12. 12 So we need two vectors: •vector of strings to store the names: vector<string> nameVec; •vector of doubles to store the scores: vector<double> scoreVec; Now we need to: • fill these vectors from the file of names and scores • compute the average of the scores in scoreVec • output the names in nameVec, the scores in scoreVec, and the differences between the scores and the average. Since none of these operations are built into C++, we will write functions to perform them.
  • 13. Function #1: fillVectors() This function should receive from its caller the name of the input file, an (empty) vector of strings, and an (empty) vector of doubles. It should open an ifstream to the file. Then, using an input loop, the function should read a name and score, append the name to the vector of strings, and append the score to the vector of doubles. On exiting the loop, the function should pass the name-vector and score-vector back to the caller. 13 as in Slide #4
  • 14. • It must pass back two vectors, so these must be reference parameters. • It must repeatedly read a name and a score and then append the name to the vector of names, and the score to the vector of scores. The vector class template provides a built-in operation for this: vecName.push_back(value); 14 See "C++ vector Library Quick Reference" link on CS 104 Other Course Information page. Also, §12.6. Observations about fillVectors()
  • 15. //-- Needs <ifstream>, <cassert>, and <vector> libraries void fillVectors(string inFileName, vector<string> & nameVec, vector<double> & scoreVec) { // open input stream to inFileName ifstream fin(inFileName.data()); assert(fin.is_open()); 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 } fin.close(); } 15 Definition of fillVectors()
  • 16. 16 Function #2: average() This function should receive from its caller a vector of doubles. It must then compute the average of these doubles, and return this average.
  • 17. • To avoid having to copy this (potentially large) vector, we make it a constant reference parameter instead of a value parameter. • To compute the average score, we need to know how many scores there are; vector has a built-in function member for this: vecName.size(); • We need the sum of the scores in scoreVec. Like arrays, vectors have a subscript operator [ ], so we could just use a for-loop for this: double sum = 0; for (int i = 0; i < scoreVec.size(); i++) sum += scoreVec[i]; However, C++ has a function that does this. 17 Observations about average()
  • 18. The accumulate() function can be used to sum the values in a C++ container — vector, in particular. It is found in the <numeric> library (possibly in <algorithm> in older versions of C++). Pattern: 18 sum = accumulate(vec.begin(), // start vec.end(), // stop 0.0); // initial // value iterators: begin() points to first element, end() points just past last element, Initial value of sum; it also determines the type of the sum (int or double) See "C++ algorithm Library Quick Reference" link on CS 104 Other Course Information page. Also, §12.7.
  • 19. // Needs <vector> and <numeric> libraries double average( vector<double> numberVec) { int numValues = numberVec.size(); if (numValues > 0) { double sum = return sum / numValues; } else { cerr << "n*** Average: vector is empty!n" << endl; return 0.0; } } 19 accumulate(numberVec.begin(), numberVec.end(), 0.0); Definition of average() Note: On the assignment, you will be building a useful library named DoubleVectorOps that contains this function average() along with functions for computing standard deviation and median. const &
  • 20. 20 Function #3: displayResults() This function should receive from its caller a vector of names, a vector of scores, and an average. It should then use a loop to output each name, its corresponding score, and the difference of the score from the average.
  • 21. • Because it returns no value, like function #1, this will be a void function that receives the two vectors — the names and the scores — and the average score. • Again, to avoid having to copy potentially large vectors, we make them constant reference parameters instead of value parameters. • We can use a for-loop to run through the two vectors and output each name, the corresponding score, and the difference between that score and the average, using the subscript operator [ ] to access the individual names and scores (see slide #17). 21 Observations about displayResults()
  • 22. 22 Definition of displayResults() // Needs <vector> library void displayResults(const vector<string> & names, const vector<double> & scores, double theAverage) { for (int i = 0; i < names.size(); i++) cout << names[i] << 't' << scores[i] << 't' << scores[i] - theAverage << endl; }
  • 23. Discussion Now that all of the operations required by our main function's algorithm exist, we are ready to implement it. 23
  • 24. Main Function Coding /* processScores.cpp ... ----------------------*/ #include <iostream> // cin, cout, ... #include <fstream> // ifstream, ... #include <string> // string #include <cassert> // assert() #include <vector> // vector #include <numeric> // accumulate() using namespace std; // local prototypes void fillVectors(string inFileName, vector<string> & nameVec, vector<double> & scoreVec); double average(const vector<double> & numberVec); void displayResults(const vector<string> & names, const vector<double> & scores, double theAverage); 24
  • 25. int main() { cout << "nTo process the names and scores in an input file," << "n enter the name of the file: "; string inFileName; getline(cin, inFileName); vector<string> nameVec; vector<double> scoreVec; fillVectors(inFileName, nameVec, scoreVec); // input double theAverage = average(scoreVec); // process displayResults(nameVec, scoreVec, theAverage ); // output } // Definitions of fillVectors(), average(), displayResults() go here 25
  • 26. Testing To test our program, we use a text editor and create easy-to-check input files: Ann 90 Bob 70 Chris 80 If we name this particular file test1.txt, then for it, our program should display: Ann 90 10 Bob 70 -10 Chris 80 0 26
  • 27. Some Other Useful & Powerful Functions You should explore the standard C++ libraries <algorithm> and <numeric> to see some of the functions you can “plug into” your programs and save yourself hours of coding and testing if you had to write them yourself. Also, these powerful functions use the most efficient methods known for carrying out operations. And they have been thoroughly tested so they can be used with confidence. 27
  • 28. One that you will learn about in the assignment is the sort() function in the <algorithm> library. It uses one of the fastest, if not the fastest, sorting methods. And like the other library functions, it is very easy to use because they use iterators in much the same way as the accumulate() function. For example, to sort the scores in our example, we need only write: sort(scoreVec , scoreVec ); 28 .begin() .end()
  • 29. Figure 12.2 Out-of-Range Errors. /* Program to demonstrate aberrant behavior resulting from out-of-range errors. ----------------------------------------------------*/ #include <iostream> // cout, << #include <iomanip> // setw() using namespace std; const int CAPACITY = 4; typedef int IntArray[CAPACITY]; void printArray(char name, IntArray x, int numElements); int main() { IntArray a = {0, 1, 2, 3}, b = {4, 5, 6, 7}, c = {8, 9, 10, 11}; int below = -3, above = 6; printArray('a', a, 4); printArray('b', b, 4); printArray('c', c, 4); b[below] = -999; b[above] = 999; cout << endl; printArray('a', a, 4); printArray('b', b, 4); printArray('c', c, 4); } /* printArray() displays an int array. Receives: name, a character, and x, an int array Output: name of array, and 4 values stored in it --------------------------------------------------------*/ void printArray(char name, IntArray x, int numElements) { cout << name << " = "; for (int i = 0; i < numElements; i++) cout << setw(5) << x[i]; cout << endl; } Sample run: a = 0 1 2 3 b = 4 5 6 7 c = 8 9 10 11 a = 0 1 999 3 b = 4 5 6 7 c = 8 -999 10 11
  • 30. Algorithm for average(): 1.Receive numVec. 2.Compute sum, the sum of the values in numVec. 3.Compute numValues, the number of values in numVec. 4.If numValues > 0: Return sum / numValues. Otherwise 1.Display an error message via cerr. 2.Return 0.0 as a default value. 5.End if. Algorithm for fillVectors(): 1.Receive inFileName, nameVec and scoreVec. 2.Open inStream, a stream to inFileName, and check that it opened successfully. 3.Loop 1.Read name and score from inStream. 2.If end-of-file was reached, terminate repetition. 3.Append name to nameVec. 4.Append score to scoreVec. 4.End loop. 5.Close inStream.
  • 31. Main Function Coding /* processScores.cpp ... ----------------------*/ #include <iostream> // cin, cout, ... #include <fstream> // ifstream, ... #include <string> // string #include <cassert> // assert() #include <vector> // vector #include <numeric> // accumulate() using namespace std; // local prototypes void fillVectors(string inFileName, vector<string> & nameVec, vector<double> & scoreVec); double average(const vector<double> & numberVec); void displayResults(const vector<string> & names, const vector<double> & scores, double theAverage); 31
  • 32. int main() { cout << "nTo process the names and scores in an input file," << "n enter the name of the file: "; string inFileName; getline(cin, inFileName); vector<string> nameVec; vector<double> scoreVec; fillVectors(inFileName, nameVec, scoreVec); // input double theAverage = average(scoreVec); // process displayResults(nameVec, scoreVec, theAverage ); // output } // Definitions of fillVectors(), average(), displayResults() go here 32
  • 33. //-- Needs <ifstream>, <cassert>, and <vector> libraries void fillVectors(string inFileName, vector<string> & nameVec, vector<double> & scoreVec) { // open input stream to inFileName ifstream fin(inFileName.data()); assert(fin.is_open()); 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 } fin.close(); } 33 Definition of fillVectors()
  • 34. // Needs <vector> and <numeric> libraries double average( vector<double> numberVec) { int numValues = numberVec.size(); if (numValues > 0) { double sum = return sum / numValues; } else { cerr << "n*** Average: vector is empty!n" << endl; return 0.0; } } 34 accumulate(numberVec.begin(), numberVec.end(), 0.0); Definition of average() const &
  • 35. 35 Definition of displayResults() // Needs <vector> library void displayResults(const vector<string> & names, const vector<double> & scores, double theAverage) { for (int i = 0; i < names.size(); i++) cout << names[i] << 't' << scores[i] << 't' << scores[i] - theAverage << endl; }