Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deque.resize() from the *front*?

Tags:

c++

deque

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?)

like image 321
user541686 Avatar asked Dec 27 '22 02:12

user541686


2 Answers

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.

like image 40
eq- Avatar answered Dec 29 '22 17:12

eq-


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())

like image 186
James McNellis Avatar answered Dec 29 '22 15:12

James McNellis