指向移位数组C ++的指针

时间:2009-11-01 03:45:23

标签: c++

我试图尽可能高效地移动我的阵列。我现在使用指针,我很难将值分配回我的数组:

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
                 nRotations--; // decrement we have reached the end
             }
        }

    } 
}

1 个答案:

答案 0 :(得分:4)

c ++在<algorithm>中内置了一个函数。只需致电std::rotate(front_ptr, front_ptr + N, back_ptr);