(c++)STL矢量的STL矢量

(c++) STL Vector of STL Vectors

本文关键字:STL 矢量 c++      更新时间:2023-10-16

我正在用一个通用向量的通用向量(vector<vector<T>>(实现一个Matrix
我的构造函数接收一个向量向量,并使用库提供的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.";
}
}

您查看向量的第一个元素,并将其与_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,以避免隐式类型转换。

编辑:同样值得一看:为什么"使用命名空间std"被认为是一种糟糕的做法?