簡體   English   中英

向量合並向量

[英]Merging vector of vectors

我的課是

    class aMatrix {
private:
    std::vector<std::vector<double> > mat;
    unsigned rows;
    unsigned cols; ...}

我想使用方法合並兩個矩陣

aMatrix aMatrix::merge(const aMatrix& ob){
    this->mat.reserve(this->mat.size()+ob.mat.size());
    this->cols+=ob.cols;
    this->mat.insert(this->mat.end(), ob.mat.begin(),ob.mat.end());
    return *this;
}

但它不起作用。 有什么想法使它起作用嗎?

編輯:沒有錯誤。 它只添加〜0列,然后添加不同於ob.mat的值。

編輯:

aMatrix mat1(3,3);
mat1(0, 0) = 1;
mat1(0, 1) = 1;
mat1(0, 2) = 1;
mat1(1, 0) = 2;
mat1(1, 1) = 3;
mat1(1, 2) = 5;
mat1(2, 0) = 11;
mat1(2, 1) = 0;
mat1(2, 2) = 5;
aMatrix ones(3,3);
ones(0,0)=1;
ones(1,1)=1;
ones(2,2)=1;

mat1.merge(ones);

結果是:

1, 1, 1, 1.11319e-308, 2, 3, 
2, 3, 5, 1.11318e-308, 11, 0, 
11, 0, 5, 1.11317e-308, 1, 0, 

編輯:如何使它以這種表示形式工作?

// Parameter Constructor
aMatrix::aMatrix(unsigned _rows, unsigned _cols, const double& _initial) {
    mat.resize(_rows);
    for (unsigned i = 0; i < mat.size(); i++) {
        mat[i].resize(_cols, _initial);
    }
    rows = _rows;
    cols = _cols;
}

編輯:確定,現在可以使用。 正確的代碼:

aMatrix& aMatrix::merge(const aMatrix& ob){
this->mat.reserve(this->mat.size()+ob.mat.size());
this->cols+=ob.cols;
for (unsigned i = 0; i < this->mat.size(); i++) {
    this->mat[i].insert(this->mat[i].end(), ob.mat[i].begin(),ob.mat[i].end() );
}
return *this;
}

謝謝 :)

您應該逐行合並。 您在代碼中所做的就是在原始矩陣中添加更多行。 您打算做的是在原始矩陣中添加更多列。

暫無
暫無

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

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