C++ for-loop - size_type vs. size_t

前端 未结 4 1222
孤独总比滥情好
孤独总比滥情好 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:57

    Yes you can use int, but only the type vector::size_type guarantees that its type can be used to index all vector elements.

    It may or may not be the same size as int. Eg, when compiling for 64-bit Windows, int is 32-bit wide, whereas vector::size_type will be 64-bit wide.

    Instead of using the rather verbose vector::size_type, you could use std::size_t, as the former is a typedef for the latter. However, if you ever happen to change the container type, then its size_type maybe a different type, and you may have to modify your code if it uses std::size_t.

提交回复
热议问题