Overloaded +=

Say if i wanted to convert the following function to an overlaoded +=:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void addvec(vector<int>& v1, vector<int>& v2)

{

if (v1.size() > v2.size())
	v2.resize(v1.size());
else if (v2.size() > v1.size())
	v1.resize(v1.size());


while (x < v1.size())
{ v1.at(x) = v1.at(x) + v2.at(x);

x++
}



Something tells me that you can't just do this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
operator+=(vector<int>& v1, vector<int>& v2)

{
if (v1.size() > v2.size())
	v2.resize(v1.size());
else if (v2.size() > v1.size())
	v1.resize(v1.size());


while (x < v1.size())
{ v1.at(x) = v1.at(x) + v2.at(x);

x++
}



but should do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vector<int>& operator+=(vector<int>& v1, vector<int>& v2)

{
if (v1.size() > v2.size())
	v2.resize(v1.size());
else if (v2.size() > v1.size())
	v1.resize(v1.size());


while (x < v1.size())
{ v1.at(x) = v1.at(x) + v2.at(x);

x++
}

return v1;
}



is that correct? My brain i triggering against the first because doesn't assignment have to return something in case of future assignment?
Last edited on
Well the first operator is obviously wrong since it has to have a return type. Your second is fine except that you should be taking the second parameter by const reference (you aren't modifying it).
Many thanks Zhuge
Might want to have a look at this line: v1.resize(v1.size());
And this: v1.at(x) = v1.at(x) + v2.at(x);
at() performs a range check, even though you just made sure that the index will always be valid.
Topic archived. No new replies allowed.