size_t vs int警告 [英] size_t vs int warning
问题描述
我一直在遵循以下代码类型的警告。
I am getting following warning always for following type of code.
std::vector v;
for ( int i = 0; i < v.size(); i++) {
}
警告C4267:正在初始化:从 size_t转换为 int,可能会丢失数据
我知道 size()
返回 size_t
,只是想知道这样可以安全地忽略此警告,还是我应将所有循环变量设置为 size_t
I understand that size()
returns size_t
, just wanted to know is this safe to ignore this warning or should I make all my loop variable of type size_t
推荐答案
如果您的向量中可能需要容纳超过 INT_MAX
个项目,请使用 size_t
。在大多数情况下,这并不重要,但是我使用 size_t
只是为了消除警告。
If you might need to hold more than INT_MAX
items in your vector, use size_t
. In most cases, it doesn't really matter, but I use size_t
just to make the warning go away.
更好的方法是使用迭代器:
Better yet, use iterators:
for( auto it = v.begin(); it != v.end(); ++it )
(如果编译器不支持C ++ 11,请使用 std :: vector< whatever> :: iterator
代替 auto
)
(If your compiler doesn't support C++11, use std::vector<whatever>::iterator
in place of auto
)
C ++ 11还使选择最佳索引类型变得更加容易(以防您在某些计算中使用索引,而不仅仅是下标 v
):
C++11 also makes choosing the best index type easier (in case you use the index in some computation, not just for subscripting v
):
for( decltype(v.size()) i = 0; i < v.size(); ++i )
这篇关于size_t vs int警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!