gpt4 book ai didi

c++ - 原地轮换C++实践

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:50:52 27 4
gpt4 key购买 nike

我有一个适用于我的“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++,并且知道它们周围有许多函数,这些函数已经被编程为执行此操作...我正在尝试“构建我自己的”。我想我在语法上已经把它记下来了,但效率总是我挣扎的地方。作为一个新手,我将非常感谢对这方面的批评..

最佳答案

旋转数组中的元素有一个老技巧(我第一次看到它是在编程珍珠中)

假设您要将数组向左旋转三个元素。

先反转前三个元素,再反转剩下的元素,再反转整个数组。

Starting Array:
1 2 3 4 5 6 7

After reversing the first three elements
3 2 1 4 5 6 7

After reversing the remaining elements
3 2 1 7 6 5 4

Finally reverse the entire array to get the final rotated array
4 5 6 7 1 2 3

数组的反转部分可以就地完成,因此您不需要任何额外的内存。

关于c++ - 原地轮换C++实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1717288/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com