gpt4 book ai didi

c++ - std::array中的size_t模板参数

转载 作者:行者123 更新时间:2023-12-01 15:12:27 34 4
gpt4 key购买 nike

std::array模板参数为template < class T, size_t N > class array;,其中N表示数组中元素的数量。
我的疑问是为什么类型std::size_t? std::size_t不是以字节为单位的对象/指针大小的别名。 std::size_t
为什么在这里用来表示std::array中元素的数量?

最佳答案

std::size_t类型定义为一种数字类型,可以表示最大可能对象的大小(例如N个字节)。
最大的对象可以是一个数组,因此对象数最多的数组就是N char的数组。
因此, std::size_t makes sense for array indexes and dimensions too
您应尽可能遵守此约定,否则可能会引入错误:

std::size_t is commonly used for array indexing and loop counting. Programs that use other types, such as unsigned int, for array indexing may fail on, e.g. 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic (cppref)


我们本来可以使用 std::index_t,但是它与 std::size_t相同,所以这毫无意义。

关于c++ - std::array中的size_t模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63252262/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com