这是我的代码:
#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++) {