“move” two vectors together

老子叫甜甜 提交于 2019-11-28 17:11:41

问题


If I have two vectors and want to combine them to one, I can do it the following way:

std::vector<T> a(100); // just some random size here
std::vector<T> b(100);

a.insert(std::end(a), std::begin(b), std::end(b));

That involves copying though, which I want to avoid. Is there any way to use move-semantics to get them together?
I highly doubt it, as a vector is supposed to be contiguous. However is there any way to do it with a deque?


回答1:


Yes, use std::move:

#include <algorithm>
std::move(b.begin(), b.end(), std::back_inserter(a));

Alternatively, you can use move iterators:

a.insert(a.end(),
         std::make_move_iterator(b.begin()), std::make_move_iterator(b.end()));

Remember to #include <iterator> in both cases, and before you begin, say:

a.reserve(a.size() + b.size());

Depending on the cost of value-initialization compared to checking and incrementing the size counter, the following variant may also be interesting:

std::size_t n = a.size();
a.resize(a.size() + b.size());
std::move(b.begin(), b.end(), a.begin() + n);



回答2:


Depends on exactly what you want to move. When you move a vector, it is done by effectively swapping the internal array pointer. So you can make one vector point to the array previously owned by another vector.

But that won't let you merge two vectors.

The best you can do then is to move every individual member element, as shown in Kerrek's answer:

std::move(b.begin(), b.end(), std::back_inserter(a));

Again, this will iterate through the vector and move every element to the target vector.



来源:https://stackoverflow.com/questions/9778238/move-two-vectors-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!