Search code examples
c++vectordeque

Fastest way to add a deque onto the end of a vector?


This question is about speed.

I am using a function in the openCV libraries (in FaceRecognizer class) which requires the input of a vector. I need to build this vector by combining several deque. Are there any faster ways other than iterating through the deque and pushing back each element to the vector?

Some info about the deque: it is a deque of 15 elements where I continuously push_back and if it has 16+ elements I pop_front. Order matters.

Alternatively I could change the deque's to vectors if that might speed up everything, but from what I understand that will be slow when I delete the first element of the vector when it reaches size 16.


Solution

  • Fastest way to add a deque onto the end of a vector?

    Getting the size of the deque is possible in constant time (as for all STL containers), then reserve space in the vector to limit memory management overhead to a single allocation, finally move the elements out of the deque into the vector:

    // std::vector v, std::deque d
    v.reserve(v.size() + d.size());
    std::move(std::begin(d), std::end(d), std::back_inserter(v));
    d.clear(); // or reuse in some way
    

    If you intend to append multiple containers to the vector, consider reserveing the complete storage necessary at once.

    Watch for std::bad_alloc exceptions if the amount of data is huge. In that case using contiguous storage of a vector isn't ideal.