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)? – Oliver Charlesworth Jul 25 '15 at 17:02UTF-8
instd::string
which - oh, my! - does not exist (whilechar*
on *nix platforms is by defaultutf8
-encoded), would indeed require iterating. @ronilp You can think ofstd::string
simply as ofstd::vector<char>
.length()
hasO(1)
and simply returnsm_Length
or something like that. – Mateusz Grzejek Jul 25 '15 at 17:17