C++ for-loop - size_type vs. size_t

前端 未结 4 1213
孤独总比滥情好
孤独总比滥情好 2020-11-28 08:21

In the C++ Primer book, Chapter (3), there is the following for-loop that resets the elements in the vector to zero.

for (vector::siz         


        
4条回答
  •  星月不相逢
    2020-11-28 08:42

    You should not use intbecause vector::size_type is an unsigned type, that is, vector indexes its elements with an unsigned type. int however is a signed type and mixing signed and unsigned types can lead to weird problems. (Although it would not be a problem for small n in your example.)

    Note that I think it's clearer to just use size_t (as opposed to T::size_type) - less typing and should work on all implementations.

    Note also that the for loop you posted:

    for(size_t ix=0; ix != ivec.size(); ++ix) ...
    

    would be better written as:

    for(size_t i=0, e=ivec.size(); i!=e; ++ix) ...
    

    -- no need to call size() every iteration.

提交回复
热议问题