Suppose we have a string
std::string str; // some value is assigned
What is the difference between str.empty()
and str[0] =
Other answers here are 100% correct. I just want to add three more notes:
empty
is generic (every STL container implements this function) while operator []
with size_t
only works with string objects and array-like containers. when dealing with generic STL code, empty
is preferred.
also, empty
is pretty much self explanatory while =='\0'
is not very much.
when it's 2AM and you debug your code, would you prefer see if(str.empty())
or if(str[0] == '\0')
?
if only functionality matters, we would all write in vanilla assembly.
there is also a performance penalty involved. empty
is usually implemented by comparing the size member of the string to zero, which is very cheap, easy to inline etc. comparing against the first character might be more heavy. first of all, since all strings implement short string optimization, the program first has to ask if the string is in "short mode" or "long mode". branching - worse performance. if the string is long, dereferencing it may be costly if the string was "ignored" for some time and the dereference itself may cause a cache-fault which is costly.