【发布时间】:2009-11-11 18:48:44
【问题描述】:
我有一个适用于我的“items”int 数组的旋转函数。下面的代码完成了它,除了我不必要地传输值。我试图实现“就地”旋转。我的意思是,ptrs 将递增或递减,而不是从数组中获取值。通过这种方式,我需要以这种方式“提高”这种方法的效率水平。有什么建议吗?
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++,并且知道它们有许多浮动的函数,这些函数已经被编程为执行此操作……我正在尝试“构建我自己的”。我想我在语法上已经把它记下来了,但效率总是我挣扎的地方。作为一个新手,我将不胜感激批评这方面..
【问题讨论】: