C ++ for-loop - size_type vs. size_t [英] 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
isunsigned
integral, whileint
is not necessarilyunsigned
. :-)- it can represent the largest index, because it's unsigned.
这篇关于C ++ for-loop - size_type vs. size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!