string::size_type 而不是 int

string::size_type instead of int(string::size_type 而不是 int)

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

问题描述

const std::string::size_type cols = greeting.size() + pad * 2 + 2;

为什么是 string::size_type?int 应该可以工作!它有数字!!!

Why string::size_type? int is supposed to work! it holds numbers!!!

推荐答案

short 也包含数字.签名字符也是如此.

A short holds numbers too. As does a signed char.

但是这些类型都不能保证足够大来表示任何字符串的大小.

But none of those types are guaranteed to be large enough to represent the sizes of any strings.

string::size_type 保证了这一点.它是一种足以表示字符串大小的类型,无论该字符串有多大.

string::size_type guarantees just that. It is a type that is big enough to represent the size of a string, no matter how big that string is.

有关为什么需要这样做的简单示例,请考虑 64 位平台.一个 int 通常仍然是 32 位的,但你有远远超过 2^32 字节的内存.

For a simple example of why this is necessary, consider 64-bit platforms. An int is typically still 32 bit on those, but you have far more than 2^32 bytes of memory.

因此,如果使用(有符号)int,您将无法创建大于 2^31 个字符的字符串.然而,在这些平台上 size_type 将是一个 64 位值,因此它可以毫无问题地表示更大的字符串.

So if a (signed) int was used, you'd be unable to create strings larger than 2^31 characters. size_type will be a 64-bit value on those platforms however, so it can represent larger strings without a problem.

这篇关于string::size_type 而不是 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:string::size_type 而不是 int