std :: size_t vs size_t vs std :: string :: size_type [英] std::size_t vs size_t vs std::string::size_type

查看:114
本文介绍了std :: size_t vs size_t vs std :: string :: size_type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • size_t 在哪些地方来自没有任何内容?

  • 合理总是假设 size_t == std :: size_t

  • 我应该使用 size_type std 容器( string :: size_type vector< T> :: size_type 等)?


解决方案


当我在空项目中没有任何内容时,size_t来自哪里?


如果没有包含任何内容,则不能使用 size_t 。它定义在< stddef.h> (也可能在< cstddef> 头文件将定义放入全局命名空间以及 std )。


它合理总是假定size_t == std :: size_t?


是的。 C库中定义的所有类型和函数都包含在 std 命名空间中,只要包含适当的C ++头(例如< cstddef> ,而不是< stddef.h>


我应该何时使用std :: _ :: size_type?


$ c> size_type 在一些标准类和模板中定义的类型,例如向量?你可以使用那些,当使用这些类,如果你喜欢。在大多数情况下,你会知道它与 size_t 相同,所以你可以使用它,并保存一点打字。如果你写的是泛型代码,你不知道类是什么,那么最好使用 size_type ,以防它不兼容例如,您可能想编写一个容器,用于保存比表示的更多项目。

size_t 。您可以使用某种大数字类型来表示容器的大小,而不能转换为 size_t 。在这种情况下,像 size_t s = c.size()的代码将无法编译 - 您需要使用 Container :: size_type


  • Where does size_t come from when I don't have anything included?
  • Is it reasonable to always assume size_t == std::size_t?
  • When should I use the size_type in std containers (string::size_type, vector<T>::size_type, etc)?

解决方案

Where does size_t come from when I don't have anything included in an empty project?

If you don't have anything included, then you can't use size_t. It's defined in <stddef.h> (and perhaps also in <cstddef>, if your version of that header puts the definitions in the global namespace as well as std).

Is it reasonable to always assume size_t == std::size_t?

Yes. All types and functions defined by the C library are included in the std namespace, as long as you include the appropriate C++ header (e.g. <cstddef> rather than <stddef.h>)

When should I use std::_::size_type?

Do you mean the size_type types defined in some standard classes and templates such as vector? You could use those when using those classes if you like. In most cases, you'll know that it's the same as size_t, so you might as well use that and save a bit of typing. If you're writing generic code, where you don't know what the class is, then it's better to use size_type in case it's not compatible with size_t.

For example, you might want to write a container designed to hold more items than can be represented by size_t. You might use some kind of big number type to represent the container's size, which isn't convertible to size_t. In that case, code like size_t s = c.size() would fail to compile - you'd need to use Container::size_type instead.

这篇关于std :: size_t vs size_t vs std :: string :: size_type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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