在数组C ++中移位元素

时间:2009-10-31 20:17:49

标签: c++

我想知道为什么'intFront'中的数据不会保持不变。我在我的阵列中移动元素:

void stack::rotate(int nRotations)
{
    for (; nRotations > 0 ;) // Number of Rotations to the left
    {
        intFront = &items[top+1].n; 
        for ( int shiftL = 0; shiftL < count-1; shiftL++ )
        {
            items[shiftL] = items[shiftL+1]; // shift left from the front
        }    
        items[count-1].n = *intFront;
        nRotations--; // decrement=0 will indicate no more rotations left
    }
}

发生的事情是数组的第一个值或“head”或“front”被置于可变的“intFront”中。我按给定的旋转次数旋转所有剩余的东西,希望在最后进行简单的传输。猜不是..

3 个答案:

答案 0 :(得分:2)

  1. 你超出你的数组:在最后一次迭代中读取items[shiftL+1]超出了数组范围,
  2. 将指向结构成员的指针保存到intFront,然后在内部循环中按值覆盖这些结构 - 确保更改值intFront指向
  3. 不需要进行多次复制,即不需要两个嵌入式循环,因为您知道需要移位多少(nRotations)。

答案 1 :(得分:2)

您正在存储指向内存地址的指针,而不是值本身。因此,当您在数组中移动时,过去在该内存地址中的内容会被覆盖,但内存地址仍然是不变的。你真正想要做的是存储项目[top + 1] .n(没有&amp;在前面)的值,然后重新分配它(没有*用于解除引用)。

void stack::rotate(int nRotations)
{
    for (; nRotations > 0 ;) // Number of Rotations to the left
    {
            intFront = items[top+1].n; 
        for ( int shiftL = 0; shiftL < count-2; shiftL++ )
        {
            items[shiftL] = items[shiftL+1]; // shift left from the front
            }    
        items[count-1].n = intFront;
        nRotations--; // decrement=0 will indicate no more rotations left
    }
}

尼古拉的提示也很好 - 你不需要在两个嵌套循环( O(N ^ 2))中执行此操作;你可以用一个循环(或简单的两个顺序循环)来做,这将是 O(N)时间。

答案 2 :(得分:0)

您可以考虑使用valarray,这样可以避免手动对阵列执行移位/旋转操作。见成员函数rotate / crotate。