使用重载添加两个矩阵的最佳方法是什么?

What's the best way to add two matrices using overload?

本文关键字:最佳 方法 是什么 两个 重载 添加      更新时间:2023-10-16

我定义了一个矩阵类,并重载了+运算符,以便能够将该类的实例添加到一起。

class Matrix{
public:
vector<vector<int>> a;

Matrix & operator+(const Matrix& b)
{                
    vector<vector<int>>::const_iterator it0=b.a.begin();
    vector<vector<int>>::iterator it1=this->a.begin();
    vector<int>::iterator it2=it1->begin();
    vector<int>::iterator it3=it1->end();
    vector<int>::const_iterator it01=it0->begin();
    for(it1;it1!=this->a.end();it1++)
        {
        it2=it1->begin();
        it3=it1->end();
        it01=it0->begin();
        it0++;
             // a.begin(),a.end(),b.begin(),ret.begin()
        std::transform(it2,it3,it01,it2,std::plus<int>());
    }
            return  *this;
}
};

但是,还有另一种方法可以做到这一点,

class Matrix{
public:
vector<vector<int> > a;
Matrix & operator + (const Matrix &y) {
 for (int m=0; m<y.a.size(); ++m) {
    for (int n=0; n<y.a[0].size(); ++n) {
        this->a[m][n] = this->a[m][n] + y.a[m][n];
    }
}
return *this;
}};

第二种形式更短,但直接使用数组,而第一种形式使用迭代器。也许用迭代器可以用更短的方式实现这一点,我不确定。我用简单的案例进行了测试,它们似乎同样有效。做这件事的正确方法是什么?

对于非平凡类(例如包含std::vector的类),就地操作通常比分配新对象然后(可能)销毁其中一个或两个参数更便宜。然而,积极使用右值引用重载可以在一定程度上缓解这种情况。

请注意,无论我使用哪种函数实现,我都不会使用嵌套的std::vectors-我会使用单个std::vector或更好的std::unique_ptr<T[]>,然后将索引计算为y*w+x(记得首先对进行边界检查)。