Search code examples
c++c++11auto

C++11 auto and size_type


Given the following usage of auto:

std::vector<int> v;
for (auto i = 0; i < v.size(); ++i) {
   ...
}

It would be ideal for C++ to deduce i as std::vector<int>::size_type, but if it only looks at the initializer for i, it would see an integer. What is the deduced type of i in this case? Is this appropriate usage of auto?


Solution

  • Use decltype instead of auto to declare i.

    for( decltype(v.size()) i = 0; i < v.size(); ++i ) {
      // ...
    }
    

    Even better, use iterators to iterate over the vector as @MarkB's answer shows.