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 ?
length()
is O(n)? – Bestiarystd::string
is designed as a string with stored length. It does not have to iterate. – Plasmavector
doesn't need to iterate either (nor do most (all?) of the standard containers...) – BestiaryUTF-8
instd::string
which - oh, my! - does not exist (whilechar*
on *nix platforms is by defaultutf8
-encoded), would indeed require iterating. @Adulterant You can think ofstd::string
simply as ofstd::vector<char>
.length()
hasO(1)
and simply returnsm_Length
or something like that. – Meadsize()
is guaranteed to beO(1)
, so yes all containers. This required a change to the glibc implementation ofstd::list
. – Blowup