C strings are char arrays.
Vectors are the new arrays in C++.
Why aren't strings vectors (of chars) then?
Most of the methods of vectors and strings seem duplicated too. Is there a reason for making strings a different thing in C++?
C strings are char arrays.
Vectors are the new arrays in C++.
Why aren't strings vectors (of chars) then?
Most of the methods of vectors and strings seem duplicated too. Is there a reason for making strings a different thing in C++?
The various answers in Vector vs string show several differences in interfaces between vector
and string
, and since the typical pattern in the standard is to use static polymorphism rather than dynamic, they were created as two different classes.
Since strings do have different characteristics from vectors it doesn't seem that you would want to use public inheritance but I don't think there's anything in the standard that would prohibit protected or private inheritance, or composition to provide the underlying space management.
Additionally I suspect that string
may have been developed earlier and orthogonally to vector
which likely explains why there are member methods that more likely would have been made free algorithms if developed in parallel to vector
.
It's pretty much just historical. Strings and vectors were developed in parallel with little thought going to how they could be considered one and the same, for T==char
.
That's also why standard containers are nice and generic, whereas std::basic_string
is a total monolith of member function after member function.
Edge case optimisation opportunities since made it difficult or impossible to transform std::basic_string<T, Alloc>
into std::vector<T, Alloc>
in any sort of standard way. Take the small string optimisation, for example. Although, now that GCC's copy-on-write mechanism is officially dead, we're a little closer.
The ability to legally dereference std::string::end()
(and obtain '\0'
for your trouble) is still problematic, though. A bunch of fairly stringent iterator invalidation rules for .c_str()
basically prevent us from using std::vector<char>
for this right from the start.
tl;dr: this is what happens when you create a camel
Yes because vector is a container which can contain T and std::string is a wrapper around char* and can't contain int or other datatypes. Wouldn't make any sense to have it any other way.