<分区>
我正在尝试初始化一个矩阵,该矩阵实现为 double vector 的 vector 。即,
std::vector<std::vector<double>> A {std::vector<double> {}};
std::vector<std::vector<double>>::iterator it = A.begin();
我的想法是使用一个指向每个“行”的指针,通过这个指针访问“push_back”来填充我的行。要创建新行,我只需使用:
A.push_back(std::vector<double> {});
然后让我的指针简单地指向下一行:
it++;
然后填写我的下一行。 代码符合要求(我使用的是 C++14 标准)。但是当我运行它时,我得到了这个:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
请考虑以下代码:
#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;
}
(您可能理所当然地认为打印函数在编译或运行期间按预期工作而没有错误)。
任何输入都会有所帮助。 干杯