c++ - C++ 中的 Auto 关键字问题

标签 c++ data-structures

我写了一段代码来循环旋转一个整数数组。 例如 给定数组 - 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/

相关文章:

c++ - 在同一步骤中构建新对象和赋值

c++ - C++如何找到函数声明

c++ - 为 ARM 架构编译我的 C++ 代码

c - 需要一些关于 C 中树的解释

释放后检查结构体是否释放

C++ vector 对象.erase

c++ - 通过引用将对象传递给C++ 11中的std::thread

data-structures - 存储大型 2D 游戏世界

java - 如何将 Map 传递给 Oracle PL/SQL 函数?

Java 数据结构引用