为什么不重载operator + =()为std :: vector? [英] Why not overload operator+=() for std::vector?
问题描述
我已经开始学习C ++,所以我不知道在我缺乏知识/经验,为什么一些看起来很简单的新手,因为我要描述的东西还没有在STL中。要将向量添加到另一个向量,您必须键入:
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());
}
那么你可以
v1 += v2;
我也有这个设置为push_back到+ =单个元素到结尾。有什么理由这些事情不应该做,或者精通C ++的人特别避免?
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++?
推荐答案
我想以 append()
的重载的形式看到这个功能的情况。 operator + =
是有点模糊,你是否意味着将每个向量的元素相加?
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?
但是,就像我说的,我会欢迎: v1.append(v2);
这很清楚和简单,我不知道为什么它不在那里。
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.
这篇关于为什么不重载operator + =()为std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!