在将旋转C ++实践 [英] In Place rotation C++ Practice

查看:141
本文介绍了在将旋转C ++实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作的旋转功能去为我的项目int数组。下面的code得到它做,除了IM不必要转移出来的值。我试着去acheive了就地旋转。我的意思是那里的师生比将增加或减少,而不是抓住了array..By的价值观,我需要上升这个method..Any建议以这种方式效率水平?

I have a working rotating function going for my "items" int array. The code below gets it done, except that im transferring values out unnecessarily. Im trying to acheive the "inplace" rotation. What I mean by that is where the ptrs would increment or decrement instead of grabbing values out of the array..By which I need to "up" the efficiency level in that way for this method..Any Suggestions?

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 ++和知道他们的很多功能,左右浮动被编程已经做到这一点...我试着去建立自己的。我想我已经得到了下来语法,但效率始终是在那里我挣扎。作为一个新手,我将不胜AP preciate朝着这个方面critisim ..

Oh yes, Im trying to practice c++ and know their are many functions floating around that are programmed to do this already...Im trying to "build my own". I think i've got it down syntactically, but the efficiency is always where i struggle. As, a novice, I would greatly appreciate critisim towards this aspect..

推荐答案

有一个老把戏数组中的旋转元件(我第一次看到它的编程珠玑)

There is an old trick for rotating elements in an array (I first saw it in Programming Pearls)

假设你想通过三个要素来旋转阵​​列向左。

Say you want to rotate an array to the left by three elements.

首先扭转前三个元素,下一个反向剩余元素,再反向整个阵列

First reverse the first three elements, next reverse the remaining elements, and then reverse the entire array.

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

反转阵列的部分可以就地完成,所以你不需要任何额外的内存。

Reversing portions of the array can be done in place so you don't need any extra memory.

这篇关于在将旋转C ++实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆