Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not overload operator+=() for std::vector?

I've started learning C++, so I don't know in my lack of knowledge/experience why something so seemingly simple to a rookie as what I'm about to describe isn't already in the STL. To add a vector to another vector you have to type this:

v1.insert(v1.end(), v2.begin(), v2.end()); 

I'm wondering whether in the real world people just overload the += operator to make this less verbose, for example to the effect of

template <typename T> void operator+=(std::vector<T> &v1, const std::vector<T> &v2) {     v1.insert(v1.end(), v2.begin(), v2.end()); } 

so then you can

v1 += v2; 

I also have this set up for push_back to "+=" a single element to the end. Is there some reason these things should not be done or are specifically avoided by people who are proficient in C++?

like image 251
Lukasz Wiklendt Avatar asked Jun 16 '11 01:06

Lukasz Wiklendt


People also ask

Why we Cannot overload ternary operator?

One is that although it's technically an operator, the ternary operator is devoted primarily to flow control, so overloading it would be more like overloading if or while than it is like overloading most other operators.

Is it possible to overload operators for integers?

No we cannot overload integer or float types because overloading means to change the working of existing operators or make them to work with objects int is single member not an object.

Can we overload every operator?

Can we overload all operators? Almost all operators can be overloaded except a few.


1 Answers

This is actually a case where I would like to see this functionality in the form of an overload of append(). operator+= is kinda ambiguous, do you mean to add the elements of each vector to each other? Or you mean to append?

However, like I said, I would have welcomed: v1.append(v2); It is clear and simple, I don't know why it isn't there.

like image 99
Evan Teran Avatar answered Sep 28 '22 08:09

Evan Teran