Search code examples
c++deque

Deque removing elements from front and putting them to the back


I have a deque object of type int with a lot of elements and my task is to get all elements from the first halve of the queue and put them at the back and remove these elements from the front :for example [1,2,3,4,5] will become [3,4,5,1,2]. Currently the code that does this is :

for(int i=0;i<myDeque.size()/2;i++)
{
        int a=myDeque.front();
        myDeque.pop_front();
        myDeque.push_back(a);
}

Is there a way to optimize this process?


Solution

  • You can use std::rotate like this:

       std::rotate( myDeque.begin(), myDeque.begin() + dequeSize/2, myDeque.end()); 
    

    Complete test:

    #include <iostream>
    #include <chrono>
    #include <deque>
    #include <algorithm> // std::rotate
    
    
    void printDequeBegin(const std::deque<int>& aDeque)
    {
       auto d {aDeque.cbegin()};
       auto i {0};
       while (i < 10 && d != aDeque.cend())
       {
          std::cout << *d++ << " ";
          ++i; 
       }
       std::cout << "\n";
    }
    
    
    int main()
    {
    
       const int dequeSize { 9000000 };
       std::deque<int> myDeque;
    
       for (int i = 0; i < dequeSize; )
       {
          myDeque.push_back(++i);
       }
    
       printDequeBegin(myDeque);
    
       auto start {std::chrono::system_clock::now()};
    
       std::rotate( myDeque.begin(), myDeque.begin() + dequeSize/2, myDeque.end()); 
    
       auto end {std::chrono::system_clock::now()};
    
       auto ms {std::chrono::duration_cast<std::chrono::milliseconds>(end-start)};
       std::cout << ms.count() << " ms\n";
    
       printDequeBegin(myDeque);
    
       return 0;
    }
    

    Output:

    1 2 3 4 5 6 7 8 9 10 
    326 ms
    4500001 4500002 4500003 4500004 4500005 4500006 4500007 4500008 4500009 4500010