简体   繁体   English

std::array 中的 size_t 模板参数

[英]size_t template parameter in std::array

The std::array template parameters are template < class T, size_t N > class array; std::array 模板参数为template < class T, size_t N > class array; where N stands for the number of elements in the array.其中 N 代表数组中元素的数量。

My doubt is why is the type std::size_t ?我的疑问是为什么类型是std::size_t Isn't std::size_t an alias for the size of an object/pointer in bytes. std::size_t 不是对象/指针大小的别名(以字节为单位)。 std::size_t标准::size_t

Why is it used to denote the number of elements in std::array here?为什么这里用它来表示std::array中的元素个数?

The type std::size_t is defined to be a numeric type that can represent the size of the largest possible object (say, N bytes). std::size_t类型被定义为数字类型,可以表示最大可能的 object 的大小(例如, N字节)。

The largest object could be an array, and the array with the most possible objects is therefore an array of N char s.最大的 object 可能是一个数组,因此具有最多可能对象的数组是N char的数组。

So, std::size_t makes sense for array indexes and dimensions too .因此, std::size_t对数组索引和维度也有意义

You should stick to this convention as much as possible, because otherwise you potentially introduce bugs:你应该尽可能地遵守这个约定,否则你可能会引入错误:

std::size_t is commonly used for array indexing and loop counting. std::size_t通常用于数组索引和循环计数。 Programs that use other types, such as unsigned int , for array indexing may fail on, eg 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic ( cppref )使用其他类型(例如unsigned int )进行数组索引的程序可能会在索引超过UINT_MAX或依赖于 32 位模运算 ( cppref ) 时在 64 位系统上失败

We could have had a std::index_t instead, but it would have been the same as std::size_t , so that's pointless.我们本可以有一个std::index_t ,但它与std::size_t相同,所以这是没有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM