为什么 std::string 除了 size() 之外还有 length() 成员函数?

发布于 2024-07-22 01:42:31 字数 366 浏览 5 评论 0原文

我正在阅读 如何获取 std::string 中的字符数? 的答案并发现实际上有一个用于 std::string 的名为 length() 的方法(我总是使用 size())。

std::string 类中拥有此成员函数有什么具体原因吗? 我读过MSDN和CppReference,它们似乎表明size()length()之间没有区别。 如果是这样的话,不是会让该类的用户更加困惑吗?

I was reading the answers for How to get the number of characters in a std::string? and found that there is actually a method called length() for std::string (I always used size()).

Is there any specific reason for having this member function in the std::string class? I've 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木有鱼丸 2024-07-29 01:42:31

根据文档,这些只是同义词。 size() 是为了与其他 STL 容器(如 vectormapetc.)保持一致,并且length()是为了符合大多数人对字符串的直观概念。 人们通常谈论单词、句子或段落的长度,而不是其大小,因此 length() 的作用是使内容更具可读性。

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.

没有伤那来痛 2024-07-29 01:42:31

顺便说一句,Ruby 也一样,提供了 #length #size 作为数组和哈希中项数的同义词(C++ 只提供它用于字符串)。

我想,极简主义者和那些相信“应该有一种,最好只有一种,明显的方法来做到这一点”(正如 Python 之禅所背诵的那样)的人,我想,大多数人都会同意你的怀疑,@Naveen,而 Perl 的粉丝“有不止一种方法可以做到这一点”(或者 SQL 的语法带有无数可选的“噪音词”,给出了无数相同等价的语法形式来表达一个概念)无疑会抱怨 Ruby,尤其是 C++,只是走不远提供这种同义冗余就足够了;-)。

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).

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;-).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文