C++ for 循环 - size_type 与 size_t

2021-12-11 00:00:00 for-loop vector c++ size-type

C++ Primer 一书的第 (3) 章中,有以下 for 循环将向量中的元素重置为零.

for (vector::size_type ix = 0; ix ! = ivec.size(); ++ix)ivec[ix] = 0;

为什么使用 vector::size_type ix = 0?我们不能说 int ix = 0 吗?在第二种形式上使用第一种形式有什么好处?

谢谢.

解决方案

C++ 标准说,

<块引用>

 size_type |无符号整数类型 |可以表示最大对象的大小的类型分配模型

然后补充,

<块引用>

容器的实现在本国际中描述的标准允许假设他们的分配器模板参数满足以下两个附加条件超出表 32 中的要求.

  • typedef 成员指针、const_pointer、size_type 和差异类型是需要分别为 T*、T const*、size_t 和 ptrdiff_t

所以很可能,size_typesize_t 的 typedef.

标准真正将其定义为,

template 类分配器{上市:typedef size_t size_type;//…………};

所以需要注意的最重要的几点是:

  • size_typeunsigned 整数,而 int 不是 必然 未签名.:-)
  • 它可以表示最大的索引,因为它是无符号的.

In the C++ Primer book, Chapter (3), there is the following for-loop that resets the elements in the vector to zero.

for (vector<int>::size_type ix = 0; ix ! = ivec.size(); ++ix)
ivec[ix] = 0;

Why is it using vector<int>::size_type ix = 0? Cannot we say int ix = 0? What is the benefit of using the first form on the the second?

Thanks.

解决方案

The C++ Standard says,

 size_type  |  unsigned integral type  |  a type that can represent the size of the largest object in the
allocation model

Then it adds,

Implementations of containers described in this International Standard are permitted to assume that their Allocator template parameter meets the following two additional requirements beyond those in Table 32.

  • The typedef members pointer, const_pointer, size_type, and difference_type are required to be T*,T const*, size_t, and ptrdiff_t, respectively

So most likely, size_type is a typedef of size_t.

And the Standard really defines it as,

template <class T> 
class allocator 
{
   public:
       typedef size_t size_type;
       //.......
};

So the most important points to be noted are :

  • size_type is unsigned integral, while int is not necessarily unsigned. :-)
  • it can represent the largest index, because it's unsigned.

相关文章