Home  >  Q&A  >  body text

c++ - 既然有了size_t,那么 size_type意义何在?

#include <vector>
#include <string>
using namespace std;
int main()
{
    vector<int>::size_type a;
    vector<double>::size_type b;
    string::size_type c;
}

我在vs2015内把鼠标指针分别指向a,b,c,都是显示为size_t类型,那么既然有了size_t,为何还要size_type呢,而且还分别有这么多作用域下的size_type?说的不都是一回事么

伊谢尔伦伊谢尔伦2714 days ago572

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-17 12:07:53

    Nowadays, programming is all about portability.
    size_t is different on 32-bit and 64-bit systems. size_t is convenient for porting between systems.
    You can only use one sentence, using size_type is always correct.

     typedef size_t size_type;
    

    Do you think there is no difference?
    size_type is a supporting type (defined in the STL class). In fact, it is an unsigned int type. It only exists for the storage of the length of string and vector class objects.

     sizeof(vector<int>::size_type) 
     sizeof(string::size_type)  
     sizeof(size_t) 
    

    You can try the result of sizeof.

    Let’s take a look at include

    size_t definition:

    #include <cstddef>
    

    size_type definition:

    #include <vector>
    //或
    #include <string>
    

    reply
    0
  • Cancelreply