You need to move the elements to the deque. Code doesn't work

I need a function that shifts according to the input u index. If u is negative, shift to the right and to the left. Using the code below, the result is the deque

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 on this code, which seems to work fine in Python but not C ++, is the following:

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;
 }

      

+3


source to share


3 answers


You don't actually move it one step left or right, you move it left or right as many times as there are items. This, of course, will lead to the same order as it was.

Remove loops to get what you want to 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 as it is written. It accesses the elements moved with steps u

and stores them in another deque, returning it. What's not working with him?

+2


source


Your code can 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;
}

      

+5


source


For your second question, it (i-u) % p.size()

will be negative if u

greater than i

, since the operator %

does not change sign.

You can use instead (i - u + p.size()) % p.size()

.

+1


source







All Articles