• C++ Notes 1


    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

  • 相关阅读:
    枚举--分巧克力--蓝桥杯--二分法
    枚举笔记之哈希表 四个平方和
    枚举 蓝桥杯 四个平方数和2--暴力解法 超时
    枚举例题之平方十位数思路无代码
    LeetCode----盛最多水的容器「贪心」
    2020校招笔试
    2020校招美团点评笔试
    2020校招搜狗笔试
    2020网易校招笔试
    2020校招途家名宿开发笔试
  • 原文地址:https://www.cnblogs.com/forcheryl/p/3875784.html
Copyright © 2020-2023  润新知