size_t和size_type

照个人理解,本质上没有太大区别

  • size_t是为了平台移植,比方说一个string太长的时候,用unsigned int来修饰它的长度显然不合适了,sizeof作用是返回对象或者类型的大小,返回类型为size_t,可以理解为 足以保证存储内存中对象的大小,所以bitset.size()的返回类型也是size_t
  • size_type是容器定义的一个类型。例如vector.size()返回类型是size_type,代表容器长度。

下面是StackOverflow的一些回答

Question:Is there is a difference between size_t and container::size_type?

What I understand is size_t is more generic and can be used for any size_types.

But is container::size_type optimized for specific kinds of containers?

Answer:The standard containers define size_type as a typedef to Allocator::size_type (Allocator is a template parameter), which for std::allocator is typically defined to be size_t (or a compatible type). So for the standard case, they are the same.

However, if you use a custom allocator a different underlying type could be used. So container::size_type is preferable for maximum portability.

Answer2:

  • size_t is defined as the type used for the size of an object and is platform dependent.
  • container::size_type is the type that is used for the number of elements in the container and is container dependent.

All std containers use size_t as the size_type, but each independent library vendor chooses a type that it finds appropriate for its container.
If you look at qt, you'll find that the size_type
of Qt containers is version dependent. In Qt3 it was unsigned int
and in Qt4 it was changed to int

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容