gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:35:22 25 4
gpt4 key购买 nike

我试图将数组向左旋转,例如 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com