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

标签 c++ arrays rotation

我有一个适用于我的“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/

相关文章:

c++ - 使用参数作为 Qt 资源运行 Bash 脚本

c++ - 从 Qstring 到 std::string 的转换抛出异常

java - int 数组到 ArrayList 的转换

javascript - 匹配字符串中存在的定义标签

html - 带有背景的 CSS 旋转文本显示了一些背景问题

pdf - 如何提取 PDF 提取图像的旋转/变换信息(即查看者如何知道旋转 180 )

c++ - 如何在 C++11 中初始化 uint64_t

c++ - Boost 线程失败 BOOST_ASSERT( px != 0 );

php - Cakephp:无法将字符串偏移量用作数组

javascript - 如何使用 css3 rotate 和 setinterval 旋转图像?