On 21 Jul 2004 18:39:18 -0700,
matthew_hurne@yahoo.com (matthurne)
wrote:
[color=blue]
>I'm doing a chapter 12 exercise from Accelerated C++ ... writing a
>string-like class which stores its data in a low-level way. My class,
>called Str, uses a char array and length variable.[/color]
If you don't have a capacity member, it can be hard to write an
efficient operator>>.
I've gotten[color=blue]
>everything working that I want working so far, except for
>
>std::istream& operator>>(std::istream&, Str&)
>
>The way my Str class manages itself of course requires that the size
>of the char array to store is known when it is allocated. The problem
>is I don't know how many characters the word I'm going to store has.
>I can count them up by advancing through the stream, then allocate the
>char array with the count, but then I can't go back to the beginning
>of the word to actually store the characters into the char array once
>I've allocated it.[/color]
Right, generally you have to add the characters a char at a time.
[color=blue]
>I know I could just move through the characters in the istream and put
>them into a vector and then once I've stored a whole word, put that
>into my Str, but I don't want to do that because it renders my
>"supposed to be low-level" implementation of a string-like class
>somewhat high-level...it feels like cheating.[/color]
Depending upon how Str is meant to be used, it might be the best
approach - you don't want to unnecessarily add lots of efficent
infrastructure just to service this one function when you could use
vector instead.
[color=blue]
>I also have thrown around the idea of writing the method to store the
>word in a temp char array. I could start with a char array with only
>1 element, and then if the word being read in has another character,
>create a new char array with two elements, copy the old one in and add
>the next character. If the word is more than 2 character, then create
>a new char array with four elements, copy the old one in and add the
>next few characters until it is full again, and so on. But I'm
>avoiding that solution because then I'm basically reinventing the
>point of a vector within my method.[/color]
Indeed.
[color=blue]
>Is there another solution anyone can think of?[/color]
Add operator+=(char) to your class, and make it efficient by adding
exponential growth to your string class. e.g.
int capacity;
....
Str& operator+=(char c)
{
if (capacity < size + 1)
growString(1); //might double capacity
buffer[size] = c;
buffer[++size] = '\0'; //null terminate
return *this;
}
The above assumes that the "capacity" is the character capacity, not
memory capacity.
Tom