I have a simple class with only one member which is a vector, just like this:
class MyClass{
private:
vector<double> vector_member;
public:
method_1();
method_2();
....
};
And when I trying to overload an operator such as +=, which should add each element in the vectors in two objects and return a vector as a sum of them. My approach so far is:
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;
}
The reason that I set up a temp vector is, I need a vector with the max size of those two vectors to avoid Segmentation fault.
My problem is at each time when I try to do vector<const double>::iterator it_2 = p.vector_member.begin();
or it_2 != p.vector_member.end()
.
The vs code seems not happy with this. It says cannot convert between "__gnu_cxx::__normal_iterator<const double *, std::vector<double, std::allocator<double>>>"
and "__gnu_cxx::__normal_iterator<const double *, std::vector<const double, std::allocator<const double>>>"
I don't know how to fix this, and also is there any smart way to do this? I think my code is so broken. Thanks