Search code examples
c++swapdeque

deque, pushing the front element to the back c++


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?


Solution

  • 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:

    • use back() and memorise the value in a first variable,
    • use pop_back(),
    • use front() and memorise the value in a second variable,
    • use pop_front(),
    • use push_front() with the first variable,
    • use 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.