为size_t VS用C ++ INT和/或C [英] size_t vs int in C++ and/or C

查看:115
本文介绍了为size_t VS用C ++ INT和/或C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在C ++中的容器,它返回一个 SIZE_TYPE 而非 INT ?如果我们创建自己的结构,应该我们也被鼓励使用 SIZE_TYPE

Why is it that in C++ containers, it returns a size_type rather than an int? If we're creating our own structures, should we also be encouraged to use size_type?

推荐答案

在一般情况下,为size_t 应当你正在测量的东西的尺寸使用。这真是奇怪,为size_t 只需要重新0和 SIZE_MAX 字节和<$ C之间present $ C> SIZE_MAX 只需要为65,535 ...

In general, size_t should be used whenever you are measuring the size of something. It is really strange that size_t is only required to represent between 0 and SIZE_MAX bytes and SIZE_MAX is only required to be 65,535...

从C ++和C标准的其他有趣的约束是:

The other interesting constraints from the C++ and C Standards are:


  • 的sizeof的返回类型()为size_t ,这是一个的无符号整数

  • 运算符new()需要的字节数分配为为size_t 参数

  • 为size_t 中定义的&LT; cstddef&GT;

  • SIZE_MAX 中所定义; limits.h中&GT; 在C99,但没有提到C ++ 98? !

  • 为size_t 未列入的基本整数类型的,所以我一直认为的列表为size_t 对于基本类型中的一个类型别名:字符短整型 INT 长整型

  • the return type of sizeof() is size_t and it is an unsigned integer
  • operator new() takes the number of bytes to allocate as a size_t parameter
  • size_t is defined in <cstddef>
  • SIZE_MAX is defined in <limits.h> in C99 but not mentioned in C++98?!
  • size_t is not included in the list of fundamental integer types so I have always assumed that size_t is a type alias for one of the fundamental types: char, short int, int, and long int.

如果您计算字节,那么你一定要使用为size_t 。如果你指望元素的数量,那么你或许应该使用为size_t ,因为这似乎是C ++一直使用的是什么。在任何情况下,你不希望使用 INT - 至少是使用无符号长无符号长长如果您正在使用TR1。或... ...会更好不管你最终使用到 SIZE_TYPE 或只是的typedef 包含&LT; cstddef&GT; ,并使用的std ::为size_t

If you are counting bytes, then you should definitely be using size_t. If you are counting the number of elements, then you should probably use size_t since this seems to be what C++ has been using. In any case, you don't want to use int - at the very least use unsigned long or unsigned long long if you are using TR1. Or... even better... typedef whatever you end up using to size_type or just include <cstddef> and use std::size_t.

这篇关于为size_t VS用C ++ INT和/或C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆