Search code examples
c++dequec++03capacity

How to efficiently insert a series of values into a std::deque?


I have some C++03 code to insert a series of values into a std::deque:

void example(std::deque<int> &_recentSent,
             const int beginOffset,
             const int lastOffset) {
  for (int offset = beginOffset; offset <= lastOffset; ++offset) {
    _recentSent.push_back(offset);
  }
}

If this were a std::vector, I would use reserve() to ensure the container was large enough for all the entries to be inserted before entering the loop:

std::vector<int> _recentSent;

_recentSent.reserve(_recentSent.size() + (lastOffset + 1 - beginOffset));

But since there is not one, what might I do to efficiently insert the series of items into the std::deque so that it is only resized once if necessary?


Solution

  • Unlike in a vector, the storage for a deque is never reallocated upon appending new elements. That means that existing elements never have to be moved. Thus there is no benefit to reserving ahead of time.