need help reading this code

so here I have a function that should output the data of a file. the function's name is printDataNumbers and inside the parenthesis are its parameters that I am having trouble reading. could someone explain to me what these parameters are? why the function uses out instead of cout and what does m stand for? I think the explanation in pseudo-code would help me.


void printDataNumbers(ostream& out, vector<vector<int> >& m) {
for (int i = 0; i < m.size(); i++) {
out << "Row " << i << endl;
for (int j = 0; j < m.at(i).size(); j++) {
out << m.at(i).at(j) << " ";
}
out << endl;
}
}
Last edited on
m is the vector you passed into the function. it is a 2-d vector of integers; its like a 2-d array...
out is an output file, set up in text mode, you will write the data into it, the snip assumes the file is already open and set up and all.

so ...
cout writes to the console. out writes to the file. it is otherwise nearly identical. out is just the name, it could just as easily have been 'myfreakingfile'. Its a variable name, defined by the programmer, its not a keyword/c++ word like cout.

it should have used [] instead of .at() here. i and j are assured to be safe due to size(). .at is sluggish as it does some extra work that is bogus here.

pseudo code:
printnumstofile(file, m)
for all the rows of m
for each column of each row of m
write m[row][column] to the file, with one row per line of text in the file.

Last edited on
out writes to whatever std::ostream derived object you provide a reference to.

So (given some or other vector<vector<int>> data;)

1
2
printDataNumbers(std::cout, data);
// writes data to std::cout 


1
2
3
std::ofstream ofs("c:\\test\\out.txt");
printDataNumbers(ofs, data);
// writes data to file 


1
2
3
std::ostringstream oss;
printDataNumbers(oss, data);
// writes data to stringstream object 

Etc...

So you can use the same function to write to different outputs.

Andy

PS std::cout is not a C++ keyword; it's a variable name. For an object provided by the C++ Standard Library
http://www.cplusplus.com/reference/iostream/cout/
Last edited on
Topic archived. No new replies allowed.