首页 > 解决方案 > 我如何将向量作为类的成员进行迭代,而相应的对象作为 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>>>"

我不知道如何解决这个问题,还有什么聪明的方法可以做到这一点?我认为我的代码很糟糕。谢谢

标签: c++

解决方案


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+:复制构造您的tempfrom *this,将其向量调整为相同的max()值(这将自动零初始化任何新值),然后简单地添加另一个向量的值到副本的向量。应该是大约一半的代码。


推荐阅读