牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2016-08-01 投稿人: 浏览次数:4782

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

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

解释:

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() 一般用作返回一个序列的长度

但是无论用size还是length,返回的结果都是一样的。

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。