问题描述
在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 中的要求.
- typedef 成员指针、const_pointer、size_type 和差异类型是需要分别为 T*、T const*、size_t 和 ptrdiff_t
所以很可能,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_typeisunsignedintegral, whileintis not necessarilyunsigned. :-)- it can represent the largest index, because it's unsigned.
这篇关于C++ for 循环 - size_type 与 size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)