Answer the question
In order to leave comments, you need to log in
Why are there problems with array and container compatibility?
There is a program for calculating the sum of matrix elements (n rows, m columns) in two ways: based on the double* array and based on the container vector>
double Sum(int n, double* a)
{
double s = 0;
for (int i = 0; i < n; i++)
{
double f = a[i];
s += a[i];
}
return s;
}
double SumVectorVector(vector< vector<double> >& a)
{
double s = 0;
int sz1 = a.size();
for (int i = 0; i < sz1; i++)
{
int sz2 = a[i].size();
for (int j = 0; j < sz2; j++)
{
s += a[i][j];
}
}
return s;
}
void TestSumMatrix(int n, int m)
{
vector< vector<double> > a;
a.resize(n, vector<double>(m, 1));
cout << SumVectorVector(a) << '\t' << Sum(n * m, &a[0][0]) << endl;
}
void start()
{
int n, m;
cout << "n = ";
cin >> n;
cout << "\nm = ";
cin >> m;
cout << "\n";
TestSumMatrix(n, m);
}
Answer the question
In order to leave comments, you need to log in
Learn the materiel!
The memory buffer version assumes that the data is stored in a contiguous buffer nm×double (that is, length mn, element double).
But vector<vector> is NOT a contiguous buffer.
There is a continuous buffer n×vector<double> — the central vector. And each of the n lines separately is a continuous m×double buffer. Relative to each other in memory, they can be located anywhere.
How to fix? - the easiest
double s = 0;
for (i...) {
s += Sum(m, &a[i][0]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question