C++ string::size_type 类型
来源:互联网 发布:淘宝买到阿普唑仑片 编辑:程序博客网 时间:2024/05/20 18:45
int main()
{
string str("Hello World!/n");
cout << "The size of " << str << "is " << str.size()
<< " characters, including the newline" << endl;
return 0;
}
从逻辑上来讲,size() 成员函数似乎应该返回整形数值,或是无符号整数。但事实上,size 操作返回的是 string::size_type 类型的值。{
string str("Hello World!/n");
cout << "The size of " << str << "is " << str.size()
<< " characters, including the newline" << endl;
return 0;
}
string 类类型和许多其他库类型都定义了一些配套类型(companion type)。通过这些配套类型,库类型的使用就能与机器无关(machine-independent)。size_type 就是这些配套类型中的一种。它定义为与 unsigned 型(unsigned int 或 unsigned long)具有相同的含义,而且可以保证足够大能够存储任意 string 对象的长度。为了使用由 string 类型定义的 size_type 类型是由 string 类定义。任何存储string的size操作结果的变量必须为string::size_type 类型。特别重要的是,不要把size的返回值赋给一个 int 变量。
虽然我们不知道 string::size_type 的确切类型,但可以知道它是 unsigned 型。对于任意一种给定的数据类型,它的 unsigned 型所能表示的最大正数值比对应的 signed 型要大一倍。这个事实表明 size_type 存储的 string 长度是 int 所能存储的两倍。
使用 int 变量的另一个问题是,有些机器上 int 变量的表示范围太小,甚至无法存储实际并不长的 string 对象。如在有 16 位 int 型的机器上,int 类型变量最大只能表示 32767 个字符的 string 对象。而能容纳一个文件内容的 string 对象轻易就会超过这个数字。因此,为了避免溢出,保存一个 stirng 对象 size 的最安全的方法就是使用标准库类型 string::size_type。
string str("some string");
for (string::size_type index = 0; index != str.size(); ++index)
cout << str[index] << endl;
for (string::size_type index = 0; index != str.size(); ++index)
cout << str[index] << endl;
http://www.cppblog.com/lantionzy/archive/2009/10/22/99164.html
- C++ string::size_type 类型
- C++ string::size_type 类型
- string::size_type类型
- string::size_type类型
- C++ string::size_type 类型
- string::size_type类型
- C++ string::size_type 类型
- C++ string::size_type类型
- C++ string::size_type 类型
- string::size_type类型
- C++ string::size_type 类型
- string::size_type类型
- string::size_type 是什么定义类型?
- string对象的操作 string::size_type类型
- 【温故知新C/C++】02:string::size_type ||vector
- string::size_type
- C++ string::size_type 类型以及由此引发的思考
- vector<string>::size_type与string::size_type
- private static final long serialVersionUID = 1L;
- 最佳的线程联网类
- C#快速截屏保存成文件
- ajax原理
- Magento订单管理
- C++ string::size_type 类型
- Java处理word文档 用jacob 表格图片文字替换
- pku 1915 Knight Moves(双向广度优先搜索)
- new创建对象数组 比较 new单个对象的优点
- servlet 下配置web.xml
- 第9章 线程与内核对象的同步
- 异常了解及处理
- 级联问题
- hadoop 在windows下安装配置文章一篇