自动类型检测是否只查看一个语句

is auto type detection only looking at one statement

对于下面的两个for循环,它们是等价的吗?基本上自动查看“=0”分配并看到 iters.size() 进行比较,因此决定 iter 是类型 decltype(s.size())?

string s;
for(auto iter=0; iter<s.size();iter++)

string s;
for(decltype(s.size()) iter=0; iter<s.size();iter++)

and see iter is compared with s.size() and so decides iter is of type decltype(s.size())?

没有。 auto 仅从初始值设定项推导出类型,给定 auto iter=0;,类型从 0 推导出,那么它将是 int.

in the type specifier of a variable: auto x = expr;. The type is deduced from the initializer.

并且您可以使用 auto 指定类型,例如:

auto iter = 0u;  // unsigned int
auto iter = 0ul; // unsigned long int
auto iter = 0uz; // std::size_t, since C++23

顺便说一句,在decltype(s.size()) iter=0;中,类型会根据decltype的规则从s.size()推导出来,不受iter的影响后面也跟s.size()比较。

没有。每当变量声明具有“占位符类型”(autodecltype(auto)const auto& 等)时,只有该变量的初始值设定项用于推断实际类型。

所以在第一个片段中,iter 的类型 decltype(0)int

不,循环不等价。 auto 从初始化程序中推导出类型 only。在您的循环中,即 0 并且 0 具有类型 int。所以你的第一个循环是

for(int iter=0; iter<s.size();iter++)

而第二个循环是

for(conatiner_size_type iter=0; iter<s.size();iter++)

其中 conatiner_size_type 最有可能是 std::size_t


根据你在做什么,你可能想使用一个基于范围的 for 循环,比如

for(auto character : s)
    // loop logic
    

这将遍历字符串,character 将是循环所在字符串中当前位置的字符。