c++ - 合并 vector 的 vector

标签 c++ vector

我的类(class)是

    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;
}

谢谢:)

最佳答案

您应该逐行进行合并。您在代码中所做的是向原始矩阵添加更多行。您打算做的是向原始矩阵添加更多列。

关于c++ - 合并 vector 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29720795/

相关文章:

c++ - QMessageBox addButton() 使用标准图标/显示

c++ - 从 Vector 内部的结构获取浮点值

c++ - 使用 C++ void 函数操作 vector 数组

c++ - __declspec bare 上的 memcpy 返回意外字节

c++ - 如何在 visual studio 2015 中创建 .vcxitems

c++ - 计算整数十进制表示中不同数字的数量

c++ - 我的排序算法的时间复杂度是多少?

algorithm - 最小面积外接矩形包含凸包的最小距离轨迹

未分配 C++ vector 值

c++ - vector 析取