How to initialize the loop counter declared with the auto keyword?

  • A+
Category:Languages

Here is my code:

#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); } 

When I try to compile and run this program, I get these warnings:

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

How can I initialize these loop counters declared with auto such that the code is safe and there are no warnings?

Note that although I have a small vector here, I am trying to learn how to write safe code with auto even when the vector is so large that the value in i can exceed the range of integers.


The type of auto-declared variable is deduced from the initializer. given 2 or 0 it'll be int.

You could specify the type with explicitly typed initializer. e.g.

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: