如何初始化用auto关键字声明的循环计数器?

Lon*_*ner 6 c++ initialization declaration auto c++11

这是我的代码:

#include <iostream>
#include <vector>

void cumulative_sum_with_decay(std::vector<double>& v)
{
    for (auto i = 2; i < v.size(); i++) {
        v[i] = 0.167 * v[i - 2] + 0.333 * v[i - 1] + 0.5 * v[i];
    }
}

void printv(std::vector<double>& v)
{
    std::cout << "{";
    for (auto i = 0; i < v.size() - 1; i++) {
        std::cout << i << ", ";
    }
    std::cout << v[v.size() - 1] << "}\n";
}

int main()
{
    auto v = std::vector<double>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    cumulative_sum_with_decay(v);
    printv(v);
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译并运行此程序时,我收到以下警告:

$ clang++ -std=c++11 -Wextra foo.cpp && ./a.out
foo.cpp:6:24: warning: comparison of integers of different signs: 'int' and 'std::__1::vector<double,
      std::__1::allocator<double> >::size_type' (aka 'unsigned long') [-Wsign-compare]
    for (auto i = 2; i < v.size(); i++) {
                     ~ ^ ~~~~~~~~
foo.cpp:14:24: warning: comparison of integers of different signs: 'int' and 'unsigned long'
      [-Wsign-compare]
    for (auto i = 0; i < v.size() - 1; i++) {
                     ~ ^ ~~~~~~~~~~~~
2 warnings generated.
{0, 1, 2, 3, 4, 5, 6, 7, 8, 8.68781}
Run Code Online (Sandbox Code Playgroud)

如何初始化声明的这些循环计数器auto,以便代码是安全的并且没有警告?

请注意,尽管我在这里有一个小向量,但我正在尝试学习如何编写安全代码,auto即使向量太大以至于值i可以超过整数范围.

小智 8

您可以使用'decltype(v.size())'来获取正确的类型.

for (decltype(v.size()) i = 2; i < v.size(); i++) 
Run Code Online (Sandbox Code Playgroud)


son*_*yao 5

auto-declared变量的类型是从初始化程序推导出来的.给予20它将是int.

您可以使用显式类型化的初始值设定项指定类型.例如

for (auto i = static_cast<decltype(v.size())>(2); i < v.size(); i++) {
Run Code Online (Sandbox Code Playgroud)

  • 比编写`for(size_t i = 2; ...)`;更容易 (7认同)
  • @LoneLearner我们应该尽可能避免[c-style cast和function-style cast](/sf/answers/23246051/). (2认同)
  • @LoneLearner另见[为什么使用static_cast <int>(x)而不是(int)x?](/sf/ask/7245871/). (2认同)