c++ - 如何将数组中的元素向左旋转?

标签 c++

我试图将数组向左旋转,例如 rotateLeft3([1, 2, 3]) → [2, 3, 1]

这是我的解决方案,但由于某种原因它不起作用。有人可以解释我做错了什么吗?

#include <iostream>

using namespace std;

int main()
{
    bool six;
    int Array[3] = { 1,2,3 };
    int x = sizeof(Array) / sizeof(Array[0]);
    int temp = Array[0];
    int temp2;
    for (int i = 0; i < x; i++)
    {
        Array[i] = Array[i + 1];
        Array[x - 1] = temp;
    }
    for (int i = 0; i < 3; i++)
    {
        cout << Array[i] << endl;
    }
    system("pause");

    return 0;
}

最佳答案

这将是正确的方法。 因此,请对您的代码进行以下更改,
1) 将循环条件改为结束(x-1)(否则会越界)
2) 删除循环内的临时分配
3) 循环结束后赋值。

int temp = Array[0];
for (int i = 0; i < x-1; i++){
    Array[i] = Array[i + 1];
}
Array[x-1] = temp;

或者
如果你想使用内置模板,那么使用std::rotatealgorithm标题

关于c++ - 如何将数组中的元素向左旋转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39487792/

相关文章:

c++ - 自由字符串作为结构中的字段

c++ - AssociateColorProfileWithDevice,你从哪里得到设备名称?

c++ - 双循环变量 : unspecified or undefined? 的相等条件

c++ - WIN32内存问题(debug/release的区别)

c++ - OpenCV/C++ - 经过一些图像处理后将灰度图片转换为 BGR 图片

c++ - 运算符重载 Unresolved external 错误 LNK1120、LNK2019

c++ - QThread相关问题

c++ - MS Visual C++ 运行时库 - 有什么用?

c++ - 使用 const 键从集合中删除元素

c++ - 通过删除复制构造函数等按值(无指针)在 C++ <vector> 中存储具有相同基类的对象