Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move std::vector to std::deque in C++11

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.

like image 346
Andrew A. Avatar asked Mar 07 '16 13:03

Andrew A.


People also ask

Is deque better than vector?

Deque has some advantages associated with respect to good performance, especially for insertion and deletion at the front, whereas on the other hand, we have a vector that has some repercussions like bad performance for performing insertion and deletion from one end.

Does deque take more memory than vector?

Deque can have additional memory overhead over vector because it's made of a few blocks instead of contiguous one.

What is a std :: deque?

std::deque (double-ended queue) is an indexed sequence container that allows fast insertion and deletion at both its beginning and its end. In addition, insertion and deletion at either end of a deque never invalidates pointers or references to the rest of the elements.

Is deque slower than vector?

Performance, mainly. An std::deque has all of the functionality of std::vector , at least for normal use, but indexing and iterating over it will typically be somewhat slower; the same may hold for appending at the end, if you've used reserve .


1 Answers

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.

like image 173
Arne Avatar answered Sep 28 '22 09:09

Arne