我正在实现 Matrix
使用通用 vector 的通用 vector ( vector<vector<T>>
)。
我的构造函数接收 vector 的 vector 并使用库提供的 CCTOR 初始化数据成员。当我尝试使用聚合初始化来初始化矩阵时,以下代码行有效:
Matrix<int> mat({ {1, 2, 3} });
但是下一个没有:
Matrix<int> mat({ {1, 2, 3}, {4, 5 ,6} });
没有错误。只是一个看似无限的循环。
我显然在这里遗漏了一些东西。我的错误是什么?
这是我的矩阵定义:
template<class T>
class Matrix {
private:
int _height;
int _length;
vector<vector<T>> _val;
public:
Matrix(vector<vector<T>> val) throw (const char*) :_height(val.size()), _length((*val.begin()).size()), _val(val) {
// Checking if the rows are of different sizes.
vector<vector<T>>::iterator it = val.begin();
it++;
while (it != val.end()) {
if ((*it).size() != _length) {
throw "EXCEPTION: Cannot Create Matrix from Vectors of Different Sizes.";
}
}
}
}
还有一个输出函数,但我认为这与它没有任何关系。
最佳答案
Matrix
构造函数的定义中存在无限循环,因为您没有更新迭代器。
在这部分代码中
while (it != val.end()) {
if ((*it).size() != _length) {
throw "EXCEPTION: Cannot Create Matrix from Vectors of Different Sizes.";
}
}
您查看 vector 的第一个元素,并将其与 _length
进行比较,然后在不移动迭代器的情况下再次检查您是否位于 vector 的末尾。
要解决此问题,请将您的构造函数更改为:
Matrix(vector<vector<T>> val) throw (const char*) :_height(val.size()), _length((*val.begin()).size()), _val(val) {
// Checking if the rows are of different sizes.
auto it = val.begin();
while (it != val.end()) {
if ((*it).size() != _length) {
throw "EXCEPTION: Cannot Create Matrix from Vectors of Different Sizes.";
}
++it; // this line is added
}
}
这样你的迭代器将在每个循环中更新。另请注意,throw (const char*)
已弃用。考虑改用 noexcept(false)
。当您使用它时,应该将单参数构造函数标记为 explicit
以避免隐式类型转换。
编辑:也值得一看:Why is “using namespace std” considered bad practice?
关于c++ - (c++) STL vector 的 STL vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352970/