As per the documentation, these are just synonyms. size()
is there to be consistent with other STL containers (like vector
, map
, etc.) and length()
is to be consistent with most peoples' intuitive notion of character strings. People usually talk about a word, sentence or paragraph's length, not its size, so length()
is there to make things more readable.
A short holds numbers too. As does a signed char.
But none of those types are guaranteed to be large enough to represent the sizes of any strings.
string::size_type
guarantees just that. It is a type that is big enough to represent the size of a string, no matter how big that string is.
For a simple example of why this is necessary, consider 64-bit platforms. An int is typically still 32 bit on those, but you have far more than 2^32 bytes of memory.
So if a (signed) int was used, you'd be unable to create strings larger than 2^31 characters.
size_type will be a 64-bit value on those platforms however, so it can represent larger strings without a problem.
Best Answer
If you don't have anything included, then you can't use
size_t
. It's defined in<stddef.h>
(and perhaps also in<cstddef>
, if your version of that header puts the definitions in the global namespace as well asstd
).Yes. All types and functions defined by the C library are included in the
std
namespace, as long as you include the appropriate C++ header (e.g.<cstddef>
rather than<stddef.h>
)Do you mean the
size_type
types defined in some standard classes and templates such asvector
? You could use those when using those classes if you like. In most cases, you'll know that it's the same assize_t
, so you might as well use that and save a bit of typing. If you're writing generic code, where you don't know what the class is, then it's better to usesize_type
in case it's not compatible withsize_t
.For example, you might want to write a container designed to hold more items than can be represented by
size_t
. You might use some kind of big number type to represent the container's size, which isn't convertible tosize_t
. In that case, code likesize_t s = c.size()
would fail to compile - you'd need to useContainer::size_type
instead.