hi i am studying the Addison Wesley 's Accelerated c++ ,however i cant understand the part number 4.1.3 which says:
1 2 3 4 5 6 7 8 9 10
// read homework grades from an input stream into a vector<double>
istream& read_hw(istream& in, vector<double>& hw) {
// we must fill in this part
return in;
}
vector<double> homework;
read_hw(cin, homework);
i think every parameter we will pass in this function will be a ref to in or hw
but what does istream& means and why did we use this function and what does it do. i am a big newbie so help me please.
#include <istream> // for istream
#include <iostream> // for cin and cout
#include <vector> // for vector
std::istream& read_hw(std::istream&, std::vector<double>&); // Predeclaration
int main(int argc, char** argv[])
{
std::vector<double> homework;
read_hw(std::cin, homework);
return 0;
}
// read homework grades from an input stream into a vector<double>
std::istream& read_hw(std::istream& in, std::vector<double>& hw)
{
// we must fill in this part
return in;
}
and you will see. It does not request a cin input.
istream is an STL function used for inputting data. When reading from a file, you will typically see ifstream (In File Stream), which inherits from istream.
It appears you aren't trying to accomplish anything with returning istream ( the istream& declaration before read_hw ). If that is the case, you should replace it with void. i.e.:
#include <istream> // for istream
#include <iostream> // for cin and cout
#include <vector> // for vector
void read_hw(std::istream&, std::vector<double>&); // Predeclaration
int main(int argc, char** argv[])
{
std::vector<double> homework;
read_hw(std::cin, homework);
return 0;
}
// read homework grades from an input stream into a vector<double>
void read_hw(std::istream& in, std::vector<double>& hw)
{
// we must fill in this part
}
The & at the end is passing the reference (location of the variable) so you modify istream directly. If you don't pass the reference, you will pass a copy of istream and later functions accessing istream will get passed the original version of istream and be ignorant of anything modified by the previous function