length() returns the number of characters in the string and size() returns a size_t which is also the same but used to make it consistent with other STL containers.
For computing length(), the string iterates through all the characters and counts the length. So, O(n) time.
Is size() also the same ?
Or can size of a variable be computed directly in O(1) time ?
So, my question is, are they the same in terms of speed (as in how they are calculated) or is size computed in O(1) time ?
Using string::size: The method string::size returns the length of the string, in terms of bytes. Using string::length: The method string::length returns the length of the string, in terms of bytes. Both string::size and string::length are synonyms and return the exact same value.
sizeof() vs strlen() vs size() Data Types Supported: sizeof() gives the actual size of any type of data (allocated) in bytes (including the null values), strlen() is used to get the length of an array of chars/string whereas size() returns the number of the characters in the string.
They are the same function; they even share documentation: en.cppreference.com/w/cpp/string/basic_string/size. They're both defined to be equivalent to distance(s. begin(), s. end()), where begin() and end() are iterators over CharT elements.
The string length in C is equal to the count of all the characters in it (except the null character "\0"). For Example, the string "gfddf" has a length of 5 and the string "4343" has a length of 4.
Both have the same complexity: Constant.
From the N4431 working draft, §21.4.4
size_type size() const noexcept;Returns: A count of the number of char-like objects currently in the string. Complexity: Constant time.
And
size_type length() const noexcept;Returns: size().
[...] iterates through all the characters and counts the length [...]
That's C strings you're thinking of.
If you take a look at documentation here it says that length and size are the same.
Both string::size and string::length are synonyms and return the same value.
Also if you take a look at the code, length is cached, so the complexity is O(1). (Code from MS implementation but I'm sure other libraries are done the same way.)
size_type length() const _NOEXCEPT
{ // return length of sequence
return (this->_Mysize);
}
size_type size() const _NOEXCEPT
{ // return length of sequence
return (this->_Mysize);
}
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