首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >STL向量的(c++) STL矢量

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

Stack Overflow用户
提问于 2018-07-15 23:31:35
回答 1查看 94关注 0票数 1

我使用泛型向量( Matrix )实现一个泛型向量(vector<vector<T>>)。

我的构造函数接收向量向量,并使用库提供的CCTOR初始化数据成员。当我试图用聚合初始化初始化矩阵时,下面的代码行工作:

Matrix<int> mat({ {1, 2, 3} });

但下一个没有:

Matrix<int> mat({ {1, 2, 3}, {4, 5 ,6} });

没有错误。只是一个看似无限的循环。

很明显我在这里漏掉了什么。我犯了什么错?

这是我的矩阵定义:

代码语言:javascript
复制
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.";
            }
        }
    }
}

还有一个输出函数,但我不认为这和它有任何关系。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-15 23:52:40

Matrix构造函数的定义中有一个无限循环,因为您没有更新迭代器。

在您的代码的这一部分

代码语言:javascript
复制
while (it != val.end()) {
        if ((*it).size() != _length) {
            throw "EXCEPTION: Cannot Create Matrix from Vectors of Different Sizes.";
        }
    }

您可以查看向量的第一个元素,并将其与_length进行比较,然后检查是否再次位于向量的末尾,而不移动迭代器。

若要修复此问题,请将您的构造函数更改为:

代码语言:javascript
复制
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?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51352970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档