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

最新文章

  1. 如何一步一步用DDD设计一个电商网站(二)—— 项目架构
  2. MYSQL的JOB
  3. apache https配置步骤
  4. 求教——使用node做表单,刷新浏览器页面,浏览器为什么会重复提交上次所填的信息
  5. load-on-startup
  6. shell基础知识
  7. WIN7 WIN8 笔记本无线网卡MAC地址修改
  8. 用php生成word文档
  9. Android MediaPlayer状态机
  10. EntityFramework+Autofac+MVC+EasyUI 搭建公司基本服务项目
  11. Ext中包含了几个以get开头的方法
  12. Python3.5爬虫统计AcFun所有视频,并按各个类别进行Top100排序展示
  13. java深入浅出之数据结构
  14. BZOJ_1500_[NOI2005]维修数列_splay
  15. WebBrowser引用IE版本问题,更改使用高版本IE
  16. [20180928]ora-01426(补充).txt
  17. Spring Boot笔记之自定义启动banner
  18. SimpleDateFormat 格式化参数说明
  19. sql server 查看所有表记录数
  20. IOS tableView的一些问题总结

热门文章

  1. springboot 头像上传 文件流保存 文件流返回浏览器查看 区分操作系统 windows 7 or linux
  2. 基于CIDR的IP分组转发算法
  3. Git删除和恢复文件
  4. ionic3 pop到指定页面
  5. Spring Boot学习笔记-配置devtools实现热部署
  6. <数据挖掘导论>读书笔记5关联分析的基本概念和算法
  7. git submodule的使用
  8. 搭建简单FTP
  9. Codeforces 639B——Bear and Forgotten Tree 3——————【构造、树】
  10. php对图片加水印--将图片先缩小,再在上面加水印