Search code examples
c++stlcontainersdeque

Move an item of a container at the end (deque)


Is there any way to move the position of an item from a container?

I am interested of moving this item at the end of the deque that belongs to.

In the example above how can I move the second element at the end of the container?

std::deque<int> foo {1,2,3,4,5};

Solution

  • The only possible solution that I have thought is the following which is much different than rotate:

    template <typename T>
    void moveToEnd(typename std::deque<T> & d, typename std::deque<T>::iterator  pos)
    {
      if ( pos > d.end()-2 )
      {   
        cout << "wrong input" << endl;
        return;
      }
    
      for (auto i=pos; i!=d.end()-1; i++)
        swap(*i, *(i+1));
    }
    
    int main()
    {
    
    deque<int> deq {1,2,3,4,5,6};
    
    std::deque<int>::iterator it = deq.begin()+2;
    moveToEnd<int>(deq,it);
    //std::rotate(deq.begin(), it, deq.end());
    
    for (auto i=deq.begin(); i!=deq.end(); i++)
        cout<< *i << " ";
    
    return 0;
    }
    

    Results with my rotate: 3 4 5 6 1 2

    Results with moveToEnd: 1 2 4 5 6 3

    The result that I want is to go at the end like a bubble