C++ Notes 1 - size_type - Accelerated Ch3
1. 为什么用string::size_type而不是int?
--Why use string::size_type
? int
is supposed to work! it holds numbers!
--A short holds numbers too. So 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.
2.size_type
在标准库string类型中,最容易令人产生误解就是size()成员函数的返回值了,如果不深入分析的话,大多人都会认为size()的返回值为int类型,其实不然。事实上,size操作返回的是string::size_type类型的值。
引用《C++ Primer》一段原文简单解释一下:
string类类型和许多其他库类型都定义了一些配套类型(companion type)。通过这些配套类型,库类型的使用就能和机器无关(machine-independent)。size_type就是这些配套类型中的一种。它定义为与unsigned型(unsigned int 或 unsigned long)具有相同的含义,而且可以保证足够大能够存储任意string对象的长度。为了使用由string类型定义的size_type类型,程序员必须加上作用域操作符来说明所使用的size_type类型是由string类定义的。
特别注意的是:任何存储string的size操作结果的变量必须为string::size_type类型,同时,使用size_type类型时,必须指出该类型是在哪里定义的。切记不要吧size的返回值赋给一个int变量。
不仅string类型定义了size_type,其他标准库类型如vector::size_type,list::size_type,deque::size_type,map::size_type,multimap::size_type,basic_string::size_type 等更多请查看MSDN详细介绍。
quote:
1. http://stackoverflow.com/questions/1181079/stringsize-type-instead-of-int
2. http://blog.sina.com.cn/s/blog_8184e03301016bts.html
最新文章
- 如何一步一步用DDD设计一个电商网站(二)—— 项目架构
- MYSQL的JOB
- apache https配置步骤
- 求教——使用node做表单,刷新浏览器页面,浏览器为什么会重复提交上次所填的信息
- load-on-startup
- shell基础知识
- WIN7 WIN8 笔记本无线网卡MAC地址修改
- 用php生成word文档
- Android MediaPlayer状态机
- EntityFramework+Autofac+MVC+EasyUI 搭建公司基本服务项目
- Ext中包含了几个以get开头的方法
- Python3.5爬虫统计AcFun所有视频,并按各个类别进行Top100排序展示
- java深入浅出之数据结构
- BZOJ_1500_[NOI2005]维修数列_splay
- WebBrowser引用IE版本问题,更改使用高版本IE
- [20180928]ora-01426(补充).txt
- Spring Boot笔记之自定义启动banner
- SimpleDateFormat 格式化参数说明
- sql server 查看所有表记录数
- IOS tableView的一些问题总结