我已经为我的“items” int数组编写了一个旋转函数。下面的代码可以完成这个任务,但是我不必要地将值传递出去。我试图实现“inplace”旋转。我的意思是指指针会增加或减少,而不是从数组中获取值。通过这种方式,我需要在这种方法中提高效率水平。有什么建议吗?
void quack::rotate(int nRotations)
{
if ( count <= 1 ) return;
else // make sure our ptrs are where we want them.
{
intFrontPtr = &items[0].myInt;
intBackPtr = &items[count-1].myInt;
}
for (int temp = 0; nRotations != 0;)
{
if ( nRotations > 0 )
{
temp = *intFrontPtr;
*intFrontPtr = *intBackPtr;
*intBackPtr = temp; // Connect temps for the rotation
--intBackPtr; // Move left [...<-] into the array
}
else if ( nRotations < 0 )
{
temp = *intBackPtr;
*intBackPtr = *intFrontPtr;
*intFrontPtr = temp; // Connect temps for the rotation
++intFrontPtr; // Move right [->...] into the array
}
if ( intBackPtr == &items[0].myInt ||
intFrontPtr == &items[count-1].myInt )
{
intFrontPtr = &items[0].myInt;
intBackPtr = &items[count-1].myInt; // need to re-set
if ( nRotations > 0 ) nRotations--; // Which ways did we rotate?
else nRotations++;
}
}
}
噢,是的,我正在尝试练习C++并知道已经有许多已经编程完成的函数可以执行此操作...但我正试图“构建自己的”。我认为我在语法上已经掌握了它,但效率总是让我感到困难。作为一个新手,我非常感谢对这个方面的批评。