I am attempting to initialize a matrix that is realized as a vector of vector of doubles. I.e.,
std::vector<std::vector<double>> A {std::vector<double> {}};
std::vector<std::vector<double>>::iterator it = A.begin();
My idea is to use a pointer to each "row", access the "push_back" through this pointer to fill up my rows. To make new rows, I simply use:
A.push_back(std::vector<double> {});
And then have my pointer point to the next row by simply:
it++;
And then fill my next row. The code complies just fine (I am using C++14 standard). However when I run it, I get this:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
Please consider the following code:
#include <iostream>
#include <vector>
void print(std::vector<std::vector<double>> matrix)
{
typedef std::vector<std::vector<double>> row;
typedef std::vector<double> col;
for(row::iterator it = matrix.begin();it!=matrix.end();it++)
{
for(col::iterator ti = it->begin();ti!=it->end();ti++)
{
std::cout << *ti << ' ';
}
std::cout << '\n';
}
}
int main()
{
std::vector<std::vector<double>> A {std::vector<double> {}};
std::vector<std::vector<double>>::iterator it = A.begin();
it->push_back(1);
it->push_back(2);
it->push_back(3);
A.push_back(std::vector<double> {});
it++;
it->push_back(4);
it->push_back(5);
it->push_back(6);
print(A);
return 0;
}
(You may it for granted that the print function works as intended without errors, during compiling or runtime).
Any inputs will be helpful. Cheers