Search code examples
c++stringstdstdstringstring-length

Why does std::string have a length() member function in addition to size()?


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?


Solution

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