在C++ Primer
一书的第 (3) 章中,有以下 for 循环将向量中的元素重置为零.
for (vector::size_type ix = 0; ix ! = ivec.size(); ++ix)ivec[ix] = 0;
为什么使用 vector
?我们不能说 int ix = 0
吗?在第二种形式上使用第一种形式有什么好处?
谢谢.
C++ 标准说,
<块引用>size_type |无符号整数类型 |可以表示最大对象的大小的类型分配模型
然后补充,
<块引用>容器的实现在本国际中描述的标准允许假设他们的分配器模板参数满足以下两个附加条件超出表 32 中的要求.
所以很可能,size_type
是 size_t
的 typedef.
标准真正将其定义为,
template 类分配器{上市:typedef size_t size_type;//…………};
所以需要注意的最重要的几点是:
size_type
是 unsigned
整数,而 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
. :-)这篇关于C++ for 循环 - size_type 与 size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!