C ++ 11 auto和size_type [英] C++11 auto and size_type
本文介绍了C ++ 11 auto和size_type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于以下使用 auto
:
std :: vector< int> v;
pre>
for(auto i = 0; i< v.size(); ++ i){
...
}
这是理想的C ++推导
i
asstd :: vector< int> :: size_type
,但是如果它只查看i
的初始化器,它将看到一个整数。在这种情况下,i
的推导类型是什么?这是auto 吗?
解决方案c> decltype 而不是
auto
来声明i
。for(decltype(v.size())i = 0; i< v.size(); ++ i){
/ / ...
}
更好的做法是使用迭代器迭代向量@ MarkB的回答显示。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
asstd::vector<int>::size_type
, but if it only looks at the initializer fori
, it would see an integer. What is the deduced type ofi
in this case? Is this appropriate usage ofauto
?解决方案Use
decltype
instead ofauto
to declarei
.for( decltype(v.size()) i = 0; i < v.size(); ++i ) { // ... }
Even better, use iterators to iterate over the vector as @MarkB's answer shows.
这篇关于C ++ 11 auto和size_type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文