C ++ for-loop - size_type vs. size_t [英] C++ for-loop - size_type vs. size_t

查看:296
本文介绍了C ++ for-loop - size_type vs. size_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ Primer 书,第(3)章中,有以下for-loop将向量中的元素重置为零。

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;

为什么使用 vector< int> :: size_type ix = 0 ?我们不能说 int 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?

谢谢。

推荐答案

C ++标准说,


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


然后它添加


在此国际
标准中描述的容器
的实现允许假设
它们的Allocator模板参数
满足了表32中的额外的
要求。

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.


  • strong> typedef成员指针const_pointer,size_type和
    difference_type分别是
    需要为T *,T const *,size_t和ptrdiff_t。

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

很可能, size_type size_t 。

而且标准真的定义为

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

因此,最重要的要点是:

So the most important points to be noted are :


  • size_type 无符号整数,而 int 必须 未签名。 : - )

  • 它可以表示最大的索引,因为它是无符号的。

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

这篇关于C ++ for-loop - size_type vs. size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆