C++:string类中size()和length()的区别

此文献给好友风临神上(^-^)

结论是,两者没有任何区别。

解释:

C++ Reference中对于String字符串中函数size和length的解释是这样的:

size Return length of string
length Return length of string

连两者的具体解释都一样:

std::string::size

Return length of string

Returns the length of the string, in terms of bytes.
This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storagecapacity.
Note that string objects handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains. Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-length characters (such as UTF-8).
Both string::size and string::length are synonyms and return the same value.

std::string::length

Return length of string

Returns the length of the string, in terms of bytes.
This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storagecapacity.
Note that string objects handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains. Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-length characters (such as UTF-8).
Both string::size and string::length are synonyms and return the exact same value.

所以两者的微小区别就是:

size() 一般用作返回容器大小的方法

length() 一般用作返回一个序列的长度

❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼

❤ 点击这里 -> 订阅《从放弃C语言到使用C++刷算法的简明教程》by 柳婼

❤ 点击这里 -> 订阅PAT甲级乙级、蓝桥杯、GPLT天梯赛、LeetCode题解离线版