Reputation: 43089
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?
Upvotes: 1
Views: 100
Reputation: 272467
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.
Upvotes: 4
Reputation: 18228
Since there is no std::deque::reserve()
, what about preallocating all the storage by _recentSent.resize (_recentSent.size () + lastOffset + 1 - beginOffset)
and then inserting using iterator std::deque<int>::iterator it = _recentSent.end () - (lastOffset + 1 - beginOffset);
.
Upvotes: 0