开发者

Pointer to shift array C++

Im trying to shift my array left as efficiently as possible. Im using pointers now, and im having trouble assigning the values back into my array:

void stack::rotate(int nRotations)
{
   if ( count <= 1 ) return;

   int *intFrontPtr = &items[top+1].n;
   int *intBackPtr  = &items[count-1].n;
   int temp = 0;

   for (int shift = 0; nRotations != 0 ;)
   {
        if ( nRotations > 0 ) // we rotate left
        {  
             temp = *++intFrontPtr; // give temp the value
             items[++shift].n = temp; // debug shows success
             if ( shift == count ) // dont overrun array
             {
                 temp = *intBackPtr;
                 items[count-1].n = temp;
                 shift = 0; // reset for another rotation
                 nRotat开发者_StackOverflow社区ions--; // decrement we have reached the end
             }
        }

    } 
}


c++ has a function built in in <algorithm>. Just call std::rotate(front_ptr, front_ptr + N, back_ptr);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜