How do you resize
a std::deque
from the front instead of the back?
(Yes, of course I can push_front
a dummy value thousands of times, but is there a better/more efficient way?)
A more complete solution:
std::deque<T> deque;
std::size_t new_size = /* ... */;
if (new_size >= deque.size())
deque.insert(deque.begin(), new_size - deque.size(), T());
else
deque.erase(deque.begin(), deque.begin() + deque.size() - new_size);
Due to the nature of std::deque
, all remaining iterators should remain valid in either case.
There is an overload of insert
that inserts N elements:
std::deque<int> c;
std::size_t new_size = get_new_desired_size();
c.insert(c.begin(), new_size - c.size(), int());
(This example requires that new_size >= c.size()
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With