This is a purely theoretical question, I know that the standard containers interface are not likely to change now…
I read recently one of Herb Sutter “guru of the week” where he complained about the fact that empty() was implemented as a member function in std::string. I did not agree with all the arguments, because e.g. std::list would require a different implementation of the same function, as size() is O(n) and empty() is obviously O(1).
However, is there a reason why the standard specify that the empty() member function of (for instance) std::string is implemented as "size () == 0" instead of "begin () == end ()" ?
It seems to me that the latter allow the same O(1) implementation of the empty() function for all containers, and I can’t think of any drawback. Is it less efficient?
Thanks,
N.G.
The standard doesn’t specify exactly how anything in the library is implemented. It merely specifies the meaning of something. So if
empty()is true, thensize()must also be 0. That doesn’t mean that empty() must actually callstd::basic_string::size()and compare it to 0. The spec is simply saying that ifempty()returns true, then callingsize()immediately after will return 0, and ifempty()returned false, then callingsize()immediately after will not return 0.The spec could have said that its
begin()would equal itsend(), and it would force no implementations to change.The inconsistency is most likely a consequence of the
std::basic_stringclass having come from a different place from the rest of the STL containers during the development of C++98. That’s why it has so many member functions for doing things that STL containers would typically do with algorithms.