C++ for-loop - size_type vs. size_t(C++ for 循环 - size_type 与 size_t)
问题描述
在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_type
isunsigned
integral, whileint
is not necessarilyunsigned
. :-)- it can represent the largest index, because it's unsigned.
这篇关于C++ for 循环 - size_type 与 size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ for 循环 - size_type 与 size_t


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01