C++ vector size types

前端 未结 5 1833
醉话见心
醉话见心 2021-02-12 13:49

I just started learning C++ and have a question about vectors. The book I\'m reading states that if I want to extract the size of a vector of type double (for example), I should

5条回答
  •  时光说笑
    2021-02-12 14:07

    My personal feeling about this is that it is for a better code safety/readability.

    For me int is a type which conveys no special meaning: it can number apples, bananas, or anything.

    size_type, which is probably a typedef for size_t has a stronger meaning: it indicates a size, in bytes.

    That is, it is easier to know what a variable mean. Of course, following this rationale, there could be a lot of different types for different units. But a "buffer size" is really a common case so it somehow deserves a dedicated type.

    Another aspect is code maintability: if the container suddenly changes its size_type from say, uint64_t to unsigned int for instance, using size_type you don't have to change it in every source code relying on it.

提交回复
热议问题