Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 auto and size_type

Tags:

c++

c++11

auto

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?

like image 200
Kai Avatar asked Mar 27 '12 23:03

Kai


2 Answers

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.

like image 165
Praetorian Avatar answered Sep 24 '22 07:09

Praetorian


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.

like image 22
Mark B Avatar answered Sep 24 '22 07:09

Mark B