in c++ please Explain what each instruction in the following procedure does. voi
ID: 3914769 • Letter: I
Question
in c++ please
Explain what each instruction in the following procedure does.
void get_table(vector<vector <double> >& table)
{
int rows = table.size();
for (int r = 0; r < rows; r++) {
int columns = table[r].size();
for (int c = 0; c < columns; c++)
{
cout << "Enter value for (" << r << ", " << c << "): ";
cin >> table[r][c];
}
}
}
Explain what each of the following instructions does.
int main()
{
vector<vector <double> > m;
int rows, columns;
cout << "how many rows?: ";
cin >> rows;
m.resize(rows);
for (int r = 0; r < rows; r++)
{
cout << "how many columns for row " << r << "?: ";
cin >> columns;
m[r].resize(columns);
}
Explanation / Answer
(A)
void get_table(vector<vector <double> >& table)
{
// size() functions returns the number of elements in the vector
// the vector is a 2D vector
// It means, each element in a vector contains another vector<double>
// So, if we consider it as a 2D matrix, we are calculating the number of rows in that matric
int rows = table.size();
// traverse through the rows of the matrix
for (int r = 0; r < rows; r++)
{
// size() functions returns the number of elements in the vector
// Here, we are calculating the number of elements in the r th column in the matric
// or the r th vector<double> vector
int columns = table[r].size();
// traverse through the columns
for (int c = 0; c < columns; c++)
{
// display to the user which element value in the matric we are asking him to enter
cout << "Enter value for (" << r << ", " << c << "): ";
// get user input for the (r , c) th matrix element
cin >> table[r][c];
}
}
}
(B)
int main()
{
// the vector is a 2D vector
// It means, each element in a vector contains another vector<double> type of vector
vector<vector <double> > m;
int rows, columns;
cout << "how many rows?: ";
// get the number of rows in the matrix
cin >> rows;
// resize() function adjusts the vector according to the size passed as argument
// so here we are making rows number of rows
m.resize(rows);
// traverse through the rows
for (int r = 0; r < rows; r++)
{
cout << "how many columns for row " << r << "?: ";
// get the number of columns in the matrix
cin >> columns;
// resize() function adjusts the vector according to the size passed as argument
// so here we are making columns number of columns in the r th row of matrix
m[r].resize(columns);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.