我写了一段代码来循环旋转一个整数数组。 例如 给定数组 - 1 2 3 4 5 6 7 8 输出数组- 8 1 2 3 4 5 6 7
我面临的问题是,如果我在某些时候使用 auto 关键字,那么它会给出超出我理解的奇怪结果。谁能帮我总结一下这个问题?
#include<iostream>
#include<bits/stdc++.h>
#include <typeinfo>
using namespace std;
void rotate_one_by_one(array<int, 8> &arr)
{
auto temp = arr[arr.size() - 1];
//auto i = arr.size() - 2; // Output : 1 2 3 4 5 6 7 8
int i = arr.size() - 2; // Output : 8 1 2 3 4 5 6 7
for(; i > -1; --i)
{
arr[i+1] = arr[i];
}
arr.at(i+1) = temp;
}
void cyc_rotate(array<int, 8> &arr)
{
rotate_one_by_one(arr);
cout<<"After cyclic rotate\n";
for(auto n : arr)
cout<<n<<" ";
}
int main()
{
array<int, 8> arr = {1,2,3,4,5,6,7,8};
cyc_rotate(arr);
return 0;
}
请在我提到使用 auto 和 int 类型的输出的代码中找到注释行。如果有人仍然无法理解我想要传达的信息,请告诉我。
最佳答案
arr.size()
的返回值函数有无符号类型 std::size_t
.如果变量是 auto i
, 它变成了 std::size_t
也打字。由于它是无符号的,因此它永远不会达到低于 0 的值。
for(; i > -1; --i)
-1
在此处转换为无符号值,很可能转换为 std::numeric_limits<size_t>::max()
或 SIZE_MAX
.因为,在这种情况下,i
永远不会大于这个值,循环永远不会进入。
关于c++ - C++ 中的 Auto 关键字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56560444/