size_t vs int in C++ and/or C

后端 未结 9 1138
南方客
南方客 2020-12-01 07:51

Why is it that in C++ containers, it returns a size_type rather than an int? If we\'re creating our own structures, should we also be encouraged to

9条回答
  •  误落风尘
    2020-12-01 08:11

    All containers in the stl have various typedefs. For example, value_type is the element type, and size_type is the number stored type. In this way the containers are completely generic based on platform and implementation.

    If you are creating your own containers, you should use size_type too. Typically this is done

    typedef std::size_t size_type;
    

    If you want a container's size, you should write

    typedef vector ints;
    ints v;
    v.push_back(4);
    ints::size_type s = v.size();
    

    What's nice is that if later you want to use a list, just change the typedef to

    typedef list ints;
    

    And it will still work!

提交回复
热议问题