我使用泛型向量( Matrix )实现一个泛型向量(vector<vector<T>>)。
我的构造函数接收向量向量,并使用库提供的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.";
}
}
}
}还有一个输出函数,但我不认为这和它有任何关系。
发布于 2018-07-15 23:52:40
在Matrix构造函数的定义中有一个无限循环,因为您没有更新迭代器。
在您的代码的这一部分
while (it != val.end()) {
if ((*it).size() != _length) {
throw "EXCEPTION: Cannot Create Matrix from Vectors of Different Sizes.";
}
}您可以查看向量的第一个元素,并将其与_length进行比较,然后检查是否再次位于向量的末尾,而不移动迭代器。
若要修复此问题,请将您的构造函数更改为:
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?
https://stackoverflow.com/questions/51352970
复制相似问题