Im now practicing in working with data structures. And I have one question, can I write deque.push_back(pop_front())
, if I want to swap the first and last element in the deque?
No, you cannot, sorry.
pop_back()
has no result (void
) so it cannot be used as a parameter
for push_back()
.
( https://en.cppreference.com/w/cpp/container/deque/pop_back )
It may be better to call back()
and store the result in
a variable; then call pop_back()
.
Repeat the same procedure with a second variable and then call
push_back()
twice, with the first and the second variable.
ah?!?! the question has just changed.
The problem is the same with pop_front()
which has a void
result.
To swap the first and last element you can use
std::swap(deque.front(), deque.back())
.
If you absolutely want to use push/pop
functions then:
back()
and memorise the value in a first variable,pop_back()
,front()
and memorise the value in a second variable,pop_front()
,push_front()
with the first variable,push_back()
with the second variable,but this solution is much more complicated than std::swap()
.
Of course, for all of this, you have to ensure there are enough
elements in the deque: at least one for the std::swap()
solution,
at least two for the push/pop
solution.