c++ - Need to shift elements in deque. Code not working -


i want function shifts according input index u. if u negative, shift right, else left. using code below resulting deque same input.

deque<float> move(deque<float>p, int u) {     if(u==0 || p.size()==1)         return p;      else if(u<0)     {         for(int i=0; i<abs(p.size()); i++)         {             int temp = p.back();             p.pop_back();             p.push_front(temp);         }            }      else     {         for(int i=0; i<p.size(); i++)         {             int temp = p.front();             p.pop_front();             p.push_back(temp);         }     }      return p;   } 

another variation code seems work fine in python not in c++ this:

deque<float> move1(deque<float>p, int u) {     deque<float> q;      for(int i=0; i<p.size(); i++)         q.push_back(p[(i-u) % p.size()]);       return q;  } 

you not shifting 1 step left or right, shifting left or right many times there items. this, of course, result in same order was.

remove loops want achieve

deque<float> move(deque<float>p, int u) {     if(u==0 || p.size()==1)         return p;      else if(u<0)     {         for(int i=0; i<-u; i++)         {             int temp = p.back();             p.pop_back();             p.push_front(temp);         }     }      else     {         for(int i=0; i<u; i++)         {             int temp = p.front();             p.pop_front();             p.push_back(temp);         }     }      return p; } 

the second code should work fine written. accesses elements displaced u steps , stores them in deque, returning it. not working it?


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -