8

If I have std::deque and std::vector and want to combine them to std::deque, I can do it the following way:

typedef int T; // type int will serve just for illustration
std::deque< T > deq(100); // just some random size here
std::vector< T > vec(50);
// ... doing some filling ...
// now moving vector to the end of queue:
deq.insert( 
    deq.end(), 
    std::make_move_iterator( vec.begin() ),
    std::make_move_iterator( vec.end() )
);
std::cout << deq.size() << std::endl;

We know the size of the vector but we can't reserve memory at the end of std::deque before using std::deque.insert(...). So is it the fastest way to move all elements of std::vector to the end of std::deque? Or did I miss something?

Thank you.

Eliad
  • 894
  • 6
  • 20
Andrew A.
  • 81
  • 1
  • 3
  • When you say "moving", I think "take the elements from the vector, and put them into the deque" What you've shown still leaves the moved-from elements present in the vector. – Marshall Clow Mar 07 '16 at 20:20
  • Is T a type for which moving is supposed to be cheaper than copying? For ints that makes no difference – MikeMB Mar 10 '16 at 19:51

2 Answers2

3

try this:

using T = int; // type int will serve just for illustration

std::deque< T > deq(100); // just some random size
std::vector< T > vec(50);
// ... doing some filling ...
// now moving vector to the end of queue:
std::move( 
    begin(vec),
    end(vec),
    back_inserter(deq)
);
std::cout << deq.size() << std::endl;

Keep in mind that this still copies the vector to the end of the deq. It just applies std::move on each element of vec to the end of deq. As long as T is just an int this is not much different than copying the vector to the end of deq.

Arne
  • 7,921
  • 9
  • 48
  • 66
0

I would use resize method as follows, because than is deque reallocated only once:

size_t oldSize = deq.size();
deq.resize(deq.size() + vec.size());
copy(vec.begin(), vec.end(), deq.begin() + oldSize);
Radek
  • 518
  • 5
  • 12
  • 1
    Reallocation in a deque is not a problem. When it needs more space it adds a new block. The old data is not moved around. This is the advantage of deque over vector and also why it does not have a `reserve()`. The problem with doing a re-size first is that it forces all the elements to be constructed. Then you are doing an assignment operation on each of the elements being copied. This may not make a difference for POD like data but anything complicated this would be inefficient. – Martin York Dec 12 '17 at 21:20