c++ - 我如何将向量作为类的成员进行迭代,而相应的对象作为 const 传递
问题描述
我有一个简单的类,只有一个成员是向量,就像这样:
class MyClass{
private:
vector<double> vector_member;
public:
method_1();
method_2();
....
};
当我尝试重载 += 之类的运算符时,它应该将向量中的每个元素添加到两个对象中,并返回一个向量作为它们的总和。到目前为止,我的方法是:
MyClass& MyClass :: operator+=(const MyClass& p){
size_t n = max(this->vector_member.size(),p.vector_member.size());
MyClass temp;
for (size_t i = 0; i < n; ++i){
temp.vector_member.push_back(0);
}
vector<double>::iterator it_1 = this->vector_member.begin();
vector<const double>::iterator it_2 = p.vector_member.begin();
vector<double>::iterator it_3 = temp.vector_member.begin();
for (; it_1 != this->vector_member.end(); ++it_1, ++it_3){
*it_3 += *it_1;
}
it_3 = temp.vector_member.begin();
for (; it_2 != p.vector_member.end(); ++it_2, ++it_3){
*it_3 += *it_2;
}
return temp;
}
我设置临时向量的原因是,我需要一个具有这两个向量最大大小的向量以避免分段错误。
我的问题是每次我尝试做vector<const double>::iterator it_2 = p.vector_member.begin();
or时it_2 != p.vector_member.end()
。
vs 代码似乎对此并不满意。它说不能在"__gnu_cxx::__normal_iterator<const double *, std::vector<double, std::allocator<double>>>"
和之间转换"__gnu_cxx::__normal_iterator<const double *, std::vector<const double, std::allocator<const double>>>"
我不知道如何解决这个问题,还有什么聪明的方法可以做到这一点?我认为我的代码很糟糕。谢谢
解决方案
vector<const double>::iterator it_2 = p.vector_member.begin();
这应该是:
vector<double>::const_iterator it_2 = p.vector_member.begin();
您的向量始终是double
值向量。向量本身在这里是不变的。它确实有效地制作了向量的内容const
,但它们仍然double
是“书本”。
此外,在 C++11 后的世界中,这可以很简单:
auto it_2 = p.vector_member.begin();
让筹码落在他们可能的地方......
PS您实现的运算符从根本上被破坏的原因与您的编译错误无关:它返回对临时对象的引用。operator+
如果您返回的不是引用而是temp
值本身,而不是对它的引用,那么您确实实现了一个。Anoperator+=
应该修改自己,而不是创建一个新对象并返回它。在任何情况下,似乎有一种更简单和更短的方法来完成逻辑等效operator+
:复制构造您的temp
from *this
,将其向量调整为相同的max()
值(这将自动零初始化任何新值),然后简单地添加另一个向量的值到副本的向量。应该是大约一半的代码。
推荐阅读
- javascript - 如何在 JavaScript 中使用 OR 运算符从 Firestore 检索数据?
- node.js - 快速应用中请求响应处理的最佳实践
- bash - 使用 POSIX 提取 git url 的域
- mysql - 为什么我的sql池连接突然关闭
- jenkins - 将本地 Docker 守护进程暴露给 minikube - Jenkins config.json:系统找不到指定的路径
- python-3.x - Asyncssh 无法创建具有多个进程的通道
- spring - 错误在当前项目中找不到前缀“spring”的插件
- php - 使用 PHP 将整个 excel 文件显示为表格
- ios - Сode with sms for ios
- swift - 当firebase子快速删除时从本地字典中删除值