C++ for-loop - size_type vs. size_t

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

    The C++ Standard says,

     size_type  |  unsigned integral type  |  a type that can represent the size of the largest object in the
    allocation model

    Then it adds,

    Implementations of containers described in this International Standard are permitted to assume that their Allocator template parameter meets the following two additional requirements beyond those in Table 32.

    • The typedef members pointer, const_pointer, size_type, and difference_type are required to be T*,T const*, size_t, and ptrdiff_t, respectively

    So most likely, size_type is a typedef of size_t.

    And the Standard really defines it as,

    template  
    class allocator 
    {
       public:
           typedef size_t size_type;
           //.......
    };
    

    So the most important points to be noted are :

    • size_type is unsigned integral, while int is not necessarily unsigned. :-)
    • it can represent the largest index, because it's unsigned.

提交回复
热议问题