C++ for 循环 - size_type 与 size_t

2023-01-20C/C++开发问题
4

本文介绍了C++ for 循环 - size_type 与 size_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

C++ Primer 一书的第 (3) 章中,有以下 for 循环将向量中的元素重置为零.

for (vector::size_type ix = 0; ix ! = ivec.size(); ++ix)ivec[ix] = 0;

为什么使用 vector::size_type ix = 0?我们不能说 int ix = 0 吗?在第二种形式上使用第一种形式有什么好处?

谢谢.

解决方案

C++ 标准说,

<块引用>

 size_type |无符号整数类型 |可以表示最大对象的大小的类型分配模型

然后补充,

<块引用>

容器的实现在本国际中描述的标准允许假设他们的分配器模板参数满足以下两个附加条件超出表 32 中的要求.

  • typedef 成员指针、const_pointer、size_type 和差异类型是需要分别为 T*、T const*、size_t 和 ptrdiff_t

所以很可能,size_typesize_t 的 typedef.

标准真正将其定义为,

template 类分配器{上市:typedef size_t size_type;//…………};

所以需要注意的最重要的几点是:

  • size_typeunsigned 整数,而 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. :-)
  • it can represent the largest index, because it's unsigned.

这篇关于C++ for 循环 - size_type 与 size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6