In C++ - The Complete Reference, the author gives us a challenge after showing how he implements a custom C++ string class. Excerpt from the book:
A Challenge:
Try implementing StrType (the string class) using the STL. That is, use a container to store the characters that comprise a string. Use iterators to operate on the strings, and use the algorithms to perform the various string manipulations.
I understand the basic concept here, but am having trouble implementing it. should I do std::vector < char > and push_back for every char or something like that? What about the string manipulations? Need some help. Sample code will be accepted gratefully, or you can explain how I may be able to implement this.
Yes,
std::vector<char>sounds like a great idea. It will save you from the troubles of writing a custom destructor, copy constructor and copy assignment operator. Plus all the iterator member functions (begin,endand co.) can just delegate to thestd::vector<char>versions.Sure thing, here is how I would overload
operator+=andoperator+for the string type:There’s probably a more efficient version of
operator+, but you can figure that out on your own.