使用重载添加两个矩阵的最佳方法是什么?
What's the best way to add two matrices using overload?
我定义了一个矩阵类,并重载了+运算符,以便能够将该类的实例添加到一起。
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::vector
s-我会使用单个std::vector
或更好的std::unique_ptr<T[]>
,然后将索引计算为y*w+x
(记得首先对进行边界检查)。
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 检测win32服务创建和删除的最佳方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将线程中的数据存储到全局容器的最佳方法?
- 将一系列整数放入类的最佳方法是什么?
- 在派生类中使用基类的私有成员变量的最佳方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 将 pybind11 绑定标记为已弃用的最佳方法
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++中变量混叠的最佳方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?