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++?
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.
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 all operators? Almost all operators can be overloaded except a few.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With