簡體   English   中英

(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以避免隱式類型轉換。

編輯:還值得一看: 為什么“使用命名空間標准”被認為是不好的做法?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM