(c++)STL矢量的STL矢量
(c++) STL Vector of STL Vectors
我正在用一个通用向量的通用向量(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"被认为是一种糟糕的做法?
相关文章:
- 用C++中的CPerson(类)类型的对象初始化STL矢量
- C++STL矢量前沿值未清除
- C++-STL-矢量-为什么矢量中没有指示relocation_count的工具
- (c++)STL矢量的STL矢量
- C++STL:矢量语法
- 在STL矢量中的增强圆形缓冲液在发行版中崩溃
- 将一个STL向量有效地分配给另一个STL矢量(WSL问题)
- 包含向量引起segfault的sTL矢量
- STL矢量通过指针擦除
- Cython 带 STL 矢量和没有 NumPy 可以从其他应用程序调用,缺少什么?
- 如何将元素插入STL矢量矩阵中
- STL 矢量 push_back() 内存双倍可用
- 有效删除C STL矢量中的双重条目
- C STL矢量半恒定
- Howto在C 中使用MATLAB和STL矢量的操作员
- 如果我尝试在同一项目中使用 stl 矢量和 CUDA 推力矢量,为什么会出现链接错误
- 将文件读取到stl矢量时删除rn
- C++STL矢量:引用Push_back
- 将值从STL矢量存储到另一个矢量
- 从STL矢量的真值中随机选择索引