From http://en.cppreference.com/w/cpp/string/basic_string/size
The number of
CharT
elements in the string.
What is CharT
element?
While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation. To achieve this libc++ uses a neat trick: the size of the string is not saved as-is but rather in a special way: if the string is short (< 23 bytes) then it stores size() * 2 .
std::string actually maintains the size as one of its data member.
The size() function is consistent with other STL containers (like vector, map, etc.) and length() is consistent with most peoples intuitive notion of character strings like a word, sentence or paragraph. We say a paragraph'ss length not its size, so length() is to make things more readable.
In C++, string length really represents the number of bytes used to encode the given string. Since one byte in C++ usually maps to one character, this metric mostly means “number of characters,” too.
std::basic_string
is a class template that is defined as
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
> class basic_string;
where CharT
is the type of character stored by the string. So std::basic_string::size
returns the number of CharT
elements in the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With