c++ - 当相应的对象作为 const 传递时,我如何迭代一个 vector 作为类的成员

标签 c++

我有一个简单的类,它只有一个成员,它是一个 vector ,就像这样:

class MyClass{
private:
    vector<double> vector_member;
public:
    method_1();
    method_2();
    ....
};

当我尝试重载 += 等运算符时,它应该将两个对象的 vector 中的每个元素相加,并返回一个 vector 作为它们的总和。 到目前为止,我的方法是:

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 的原因是,我需要一个具有这两个 vector 的最大大小的 vector 以避免段错误。

我的问题是每次我尝试做 vector<const double>::iterator it_2 = p.vector_member.begin();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();

您的 vector 始终是 double 值的 vector 。 vector 本身在这里是常量。它确实使 vector 的内容有效地 const,但它们仍然是 double,“按照书本”。

此外,在后 C++11 世界中,这可以很简单:

auto it_2 = p.vector_member.begin();

让筹码落在可能的地方......

附言由于与您的编译错误无关的原因,您实现的运算符从根本上被破坏了:它正在返回对临时对象的引用。如果您返回的不是引用而是 temp 值本身,而不是对它的引用,那么您实际上实现了一个 operator+operator+=修改自身,而不是创建新对象并返回它。无论如何,似乎有一种更简单和更短的方法来完成逻辑上等效的 operator+:从 *this 复制构造你的 temp ,将其 vector 的大小调整为相同的 max() 值(这将自动对任何新值进行零初始化),然后只需将另一个 vector 的值添加到拷贝的 vector 中。应该是大约一半的代码。

关于c++ - 当相应的对象作为 const 传递时,我如何迭代一个 vector 作为类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65100648/

相关文章:

c++ - 两个不同进程c++之间的FIFO通信

c++ - 如何在 C++ 中的大端和小端值之间进行转换?

c++ - CMake 链接器找不到不以 "lib"开头的库

c++ - 如何在wxWidgets中使用wxString、数字和其他字符串类型

c++ - 如何找到激活时打开给定 HMENU 的菜单项(如果有)?

c++ - 排列数据包中的字节

java - ASN1解码器(libtasn1-3.3)打印DD证书pem的内容

c++ - 为什么 boost shared_ptr 包含带有 close() 的 header ?

c++ - mmap 只适用于小文件?

c# - 在 C# 项目中导入 C++ dll