Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to shift elements in deque. Code not working

I want a function which shifts according to input index u. If u is negative, shift right, else left. Using the code below the resulting deque is the same as the 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 to this code which seems to work fine in Python but not in C++ is 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;
 }
like image 697
Mohsin Anees Avatar asked Sep 08 '26 04:09

Mohsin Anees


1 Answers

Your code could be much simpler if you used std::rotate from the standard library. For example:

std::deque<float> move(std::deque<float> p, int u)
{
    if (u == 0 || p.empty()) {
        return p;
    }
    if (u < 0) {
        std::rotate(p.begin(), std::prev(p.end(), -u), p.end());
    } else {
        std::rotate(p.begin(), std::next(p.begin(), u), p.end());
    }
    return p;
}
like image 98
Blastfurnace Avatar answered Sep 09 '26 18:09

Blastfurnace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!