C++中的左旋转操作

left rotation operation in c++

int main()
{
    int newposition, shiftSteps;
    int numbers[10], numberscopy[10];
    cin >> shiftSteps;
    for (int i = 0; i < 10; i++)
        cin >> numbers[i];

    for (int i = 0; i < 10; i++)
        numberscopy[i] = numbers[i];

    //------------------------------------

    for (int i = 9; i >= 0; i--)
    {
        if (i - shiftSteps < 10 && i - shiftSteps >= 0)
            newposition = i - shiftSteps;
        else
            newposition = i - shiftSteps + 10;
        numbers[newposition] = numberscopy[i];
    }
    for (int i = 0; i < 10; i++)
        cout << numbers[i] << " ";
}

我想向左旋转 10 个数字,"shiftSteps" 是向左移动的次数。但我有一个问题,到目前为止我为某些数字编写的代码可以正常工作,例如 {0 1 2 3 4 5 6 7 8 9} and shiftSteps = 3 输出是 3 4 5 6 7 8 9 0 1 2。 但是如果输入是 0 1 2 3 4 5 6 7 8 9shiftSteps = 15,输出是 5 6 7 8 9 5 6 7 8 9 并且 0 消失,shiftSteps = 15 的真实答案是 5 6 7 8 9 0 1 2 3 4.

问题是 newposition = i - shiftSteps + 10; 导致 shiftSteps == 15i < 5 的负值。这会导致越界访问。

需要保证旋转量在数组元素个数以下,可以用取模运算符实现。

    shiftSteps = shiftSteps % 10;

    for (int i = 9; i >= 0; i--)
    {
        newposition = i - shiftSteps;
        if (newposition < 0)
            newposition += 10;
        numbers[newposition] = numberscopy[i];
    }

这适用于 shiftSteps 的非负值。如果你还需要处理底片,你应该相应地调整循环中的条件。

PS:另外,请注意在您的代码中 shiftSteps 未初始化。

PPS: 你也可以使用std::rotate算法。