[英]What's the best way to add two matrices using overload?
I have defined one matrix class, and overloaded the + operator to be able to add instances of this class together. 我定义了一个矩阵类,并重载了+运算符,以便能够将此类的实例添加在一起。
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;
}
};
But then, there is also another way of doing 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;
}};
The second form is shorter, but uses arrays directly, while the first one uses iterators. 第二种形式较短,但是直接使用数组,而第一种形式使用迭代器。 Maybe it's possible to do this with iterators in a shorter way, I'm not sure. 我不确定,也许可以使用更短的迭代器来完成此操作。 I've tested with simple cases and they seem to be equally efficient. 我已经测试了简单的案例,它们似乎同样有效。 What's the proper way of doing this? 这样做的正确方法是什么?
For non-trivial classes (such as classes including a std::vector
), in-place operations are often cheaper than allocating a new object and then (presumably) destroying one or both of the arguments. 对于非平凡的类(例如,包含std::vector
),就地操作通常比分配新对象然后销毁(或假定)销毁一个或两个参数要便宜。 However, aggressive use of rvalue reference overloads can somewhat mitigate this. 但是,积极使用右值引用重载可以在某种程度上缓解这种情况。
Note that regardless of which function implementation I used, I would not use nested std::vector
s - I would either use a single std::vector
or better a std::unique_ptr<T[]>
and then calculate the index as y*w+x
(remember to bounds-check first ). 请注意,无论我使用哪种函数实现,都不会使用嵌套的 std::vector
s-我会使用单个std::vector
或更佳的std::unique_ptr<T[]>
然后将索引计算为y*w+x
(记得边界检查第一 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.