C++11 auto and size_type

2020-06-16 09:17发布

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?

标签: c++ c++11 auto
4条回答
萌系小妹纸
2楼-- · 2020-06-16 09:48

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.

查看更多
Animai°情兽
3楼-- · 2020-06-16 09:54

The answer to your question "Is this appropriate usage of auto?" is no for reasons explained in other answers. For the particular case of looping through the contents of a container, you are most likely better off with a range based for-loop:

const reference access to elements, i is const int&:

std::vector<int> v;
for (const auto& i :  v ) {
   std::cout << i << "\n";
}

non-const reference access, i is int&:

std::vector<int> v;
for (auto& i :  v ) {
   ++i;
   std::cout << i << "\n";
}

value access, i is int:

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

and so on. This also works for C-style arrays.

查看更多
放荡不羁爱自由
4楼-- · 2020-06-16 09:55

auto gets the type exclusively from the initializer. No attention is paid to other uses, at least not for determining the variable's type. To take that into account as well, decltype is an option:

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

or, you may be able to rewrite the loop to go backwards:

for (auto i = v.size(); i-- != 0; )

or, you may be able to avoid the for loop entirely.

查看更多
Evening l夕情丶
5楼-- · 2020-06-16 10:00

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.

查看更多
登录 后发表回答