C++ std::string length() 和 size() 成员函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/905479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
std::string length() and size() member functions
提问by Naveen
I was reading the answers for this questionand found that there is actually a method called length()
for std::string
(I always used size()
). Is there any specific reason for having this method in std::string
class? I read both MSDN and CppRefernce, and they seem to indicate that there is no difference between size()
and length()
. If that is so, isn't it making more confusing for the user of the class?
我正在阅读这个问题的答案,发现实际上有一种方法length()
需要std::string
(我一直使用size()
)。在std::string
课堂上使用这种方法有什么具体原因吗?我阅读了 MSDN 和 CppRefernce,它们似乎表明size()
和之间没有区别length()
。如果是这样,是不是让课程的用户更加困惑?
回答by Todd Gamblin
As per the documentation, these are just synonyms. size()
is there to be consistent with other STL containers (like vector
, map
, etc.) and length()
is to be consistent with most peoples' intuitive notion of character strings. People usually talk about a word, sentence or paragraph's length, not its size, so length()
is there to make things more readable.
根据文档,这些只是同义词。 size()
在那里,以便与其他STL容器(如一致vector
,map
,等),并length()
是要与大多数人的字符串的直观概念是一致的。人们通常谈论一个词、一个句子或一个段落的长度,而不是它的大小,所以这样做length()
是为了使事情更具可读性。
回答by Alex Martelli
Ruby's just the same, btw, offering both #length
and#size
as synonyms for the number of items in arrays and hashes (C++ only does it for strings).
Ruby 是一样的,顺便说一句,提供#length
和#size
作为数组和散列中项目数的同义词(C++ 只对字符串这样做)。
Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).
极简主义者和相信“应该有一种,理想情况下只有一种明显的方法来做到这一点”(正如 Python 之禅所言)的人,我想,我猜他们大多同意你的怀疑,@Naveen,而 Perl 的粉丝“有不止一种方法可以做到这一点”(或者 SQL 的语法带有无数可选的“噪音词”,给出了无数相同的语法形式来表达一个概念)无疑会抱怨 Ruby,尤其是 C++,只是不要走得太远足以提供这种同义的冗余;-)。
回答by Morten
When using coding practice tools(LeetCode) it seems that size() is quicker than length() (although basically negligible)
在使用编码练习工具(LeetCode)时,似乎 size() 比 length() 快(虽然基本上可以忽略不计)
回答by user7817690
length of string ==how many bits that string having, size==size of those bits, In strings both are same if the editor allocates size of character is 1 byte
字符串的长度 == 该字符串有多少位,大小==这些位的大小,如果编辑器分配的字符大小为 1 个字节,则在字符串中两者都是相同的