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?
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.
Why not solve your problem with iterators? Then the problem goes away:
std::vector<int> v;
for (auto i = v.begin(); i != v.end(); ++i) {
...
}
If you want to iterate using indexes I would probably just explicitly spell out the type: You know what it is. auto is primarily used for unknown or hard-to-type template types I believe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With