将向量附加到向量
假设我有 2 个标准向量:
vector<int> a;
vector<int> b;
我们还假设它们都有大约 30 个元素。
- 如何将向量 b 添加到向量 a 的末尾?
肮脏的方法是迭代 b 并通过 vector
添加每个元素,尽管我不想这样做!
Assuming I have 2 standard vectors:
vector<int> a;
vector<int> b;
Let's also say the both have around 30 elements.
- How do I add the vector b to the end of vector a?
The dirty way would be iterating through b and adding each element via vector<int>::push_back()
, though I wouldn't like to do that!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或者
第二个变体是更通用的解决方案,因为
b
也可以是一个数组。但是,它需要 C++11。如果您想使用用户定义的类型,请使用 ADL:or
The second variant is a more generically applicable solution, as
b
could also be an array. However, it requires C++11. If you want to work with user-defined types, use ADL:这可以在向量 a 中的项没有赋值运算符(例如 const 成员)的情况下使用。
在所有其他情况下,与上述插入解决方案相比,该解决方案效率较低。
This can be used in case the items in vector a have no assignment operator (e.g. const member).
In all other cases this solution is ineffiecent compared to the above insert solution.
虽然说“编译器可以保留”,但为什么要依赖它呢?那么移动语义的自动检测又如何呢?那么容器名称与
begin
和end
的重复又如何呢?难道你不想要一些更简单的东西吗?
(向下滚动到
main
查看妙语)呵呵。
现在有了 move-data-from-rhs、append-array-to-container、appendforward_list-to-container、move-container-from-lhs,感谢 @DyP 的帮助。
请注意,由于
EnableFunctionIf<>...
技术,上述内容不会在 clang 中编译。在 clang 中此解决方法有效。While saying "the compiler can reserve", why rely on it? And what about automatic detection of move semantics? And what about all that repeating of the container name with the
begin
s andend
s?Wouldn't you want something, you know, simpler?
(Scroll down to
main
for the punchline)hehe.
Now with move-data-from-rhs, append-array-to-container, append forward_list-to-container, move-container-from-lhs, thanks to @DyP's help.
Note that the above does not compile in clang thanks to the
EnableFunctionIf<>...
technique. In clang this workaround works.如果您想将向量添加到自身,那么两种流行的解决方案都会失败:
If you would like to add vector to itself both popular solutions will fail: