string::size_type 而不是 int
const std::string::size_type cols = greeting.size() + pad * 2 + 2;
为什么string::size_type
? int
应该可以工作! 它包含数字!
const std::string::size_type cols = greeting.size() + pad * 2 + 2;
Why string::size_type
? int
is supposed to work! it holds numbers!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
空头也能容纳数字。 与签名字符一样。
但这些类型都不能保证足够大来表示任何字符串的大小。
string::size_type
保证了这一点。 它是一种足以表示字符串大小的类型,无论该字符串有多大。有关为什么需要这样做的简单示例,请考虑 64 位平台。 int 通常仍然是 32 位,但你的内存远远超过 2^32 字节。
因此,如果使用(有符号)int,您将无法创建大于 2^31 个字符的字符串。
然而,size_type 在这些平台上将是 64 位值,因此它可以毫无问题地表示更大的字符串。
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
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.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.
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.
您给出的示例
来自 Koenig 的 Accelerated C++。 随后他也说出了自己选择的理由,即:
The example that you've given,
is from Accelerated C++ by Koenig. He also states the reason for his choice right after this, namely:
嵌套的
size_type
typedef 是 STL 兼容容器的要求(std::string
恰好是),因此通用代码可以选择正确的整数类型来表示大小。在应用程序代码中使用它是没有意义的,
size_t
完全没问题(int
则不然,因为它已签名,您将收到签名/未签名的比较警告)。A nested
size_type
typedef is a requirement for STL-compatible containers (whichstd::string
happens to be), so generic code can choose the correct integer type to represent sizes.There's no point in using it in application code, a
size_t
is completely ok (int
is not, because it's signed, and you'll get signed/unsigned comparison warnings).size_t
和std::string::size_type
是相同的类型,除了一个重要的区别:如果它们都表示任意大小的值,std:: string::size_type
(std::string
的成员)使用静态常量值-1
来表示npos
。 超过字符串末尾的一位。 它告诉程序您已到达字符串的末尾。 如果您正在对字符串使用search
、find
、erase
、replace
或任何其他修改操作,或者写入如果您自己的,那么您可能更喜欢std::string::size_type
。 如果您只是迭代字符串size_t
可能没问题。size_t
andstd::string::size_type
are the same types except for one important difference: Were they both will represent a value of any size,std::string::size_type
(A member ofstd::string
) uses a static constant value of-1
to representnpos
. one past the end of the string. It tells the program that you have reached the end of the string. If you are usingsearch
,find
,erase
,replace
, or any other modifying operations on strings, or writing your own then you may want to preferstd::string::size_type
. If you are just iterating over the stringsize_t
is probably fine.