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

这是我的代码
#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);
}

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

$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,8.68781}

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

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

解决方法

自动声明的变量的类型是从初始化程序推导出来的.给定2或0它将是int.

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

for (auto i = static_cast<decltype(v.size())>(2); i < v.size(); i++) {

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...