size () function is calculated usage type stirng length, type of note return value size_type

       Logically, size () member function returns the integer value seems to be, in fact, size operation returns a value of type string :: size_type. We need to do some research of this type.

       Class string type and many other types of libraries are defined as a number of supporting types (companion type). By supporting these types, the type library will be able to use regardless of the machine (machine-independent). size_type is one of these package types. It is defined as unsigned (unsigned int or unsigned long) has the same meaning, but also capable of storing sufficient length to ensure that any string objects. In order to use a string type size_type type defined, the programmer must be added to illustrate the scope operator size_type type used by the string class definition.

      Although we do not know the exact definition of the type string :: size_type, but it can refer to unsigned type. For any given type of data, it can be represented by the maximum unsigned type positive integer greater than twice the corresponding signed type. Such as the maximum integer value expressed by unsigned int to twice the largest integer that can be represented type signed int, unsigned int This is because, the most significant bit is the sign bit indicating the sign of the number, unsigned int word 4 section, and the number of bits representing the value of this number is only the remaining 15 bits; for unsigned int, it is a 4 byte, but its value is the size of all 16 are used to indicate the number, and it can only be a positive number. This fact alone shows that, string length size_type stored int can store twice as much.

     Int string used to represent a type length there is another problem, some machines int represents the range of variables is too small, not even not store the actual length of the string objects. For example in some machines, int type only two bytes, or 16 bits in size, and the largest positive integer potential energy represented only 16 32767, if we put all the characters in a file saved to a string of all types, then it is You might exceed this maximum length. Therefore, to avoid overflow safest way to save a string object's size is to use a standard type library string :: size_type.

     E.g:

     #include<iostream>

     #include<string>

     using namespace std;

     int main ()

     {

    string strTest("This is a string!");

    string::size_type length = strTest.size();

    cout<<"The size of strTest is: "<<length<<endl;

     }

Reproduced in: https: //www.cnblogs.com/hongfenglee/archive/2012/02/14/2350836.html

Guess you like

Origin blog.csdn.net/weixin_34061555/article/details/94102379