Reputation: 341
I'm creating a hash table. Each value is a string. I have the problem of deciding what structure to use to store the string. Intuitively I thought of std::string
and char*
. But,
1), std::string
seems to use the stack if the string is short. That means it's not a good choice if my hash table is really big.
2), If using char*
then I don't know what to return if I want to change a value, for example like in the following situation: myTable[i] = changedString;
It seems in this case I'll need to implement a new string class. But I'm feeling it won't be necessary with std::string
there.
Could anyone give any suggestions/comments? Thanks!
Upvotes: 1
Views: 135
Reputation: 42103
The overhead caused by std::string
is minimal, actually AFAIK apart from the pointer to the string's internal buffer, there are just size
and capacity
members, both of type size_t
, causing let's say (it's environment dependent) 8 bytes per string, so if you have an array of 100 000 strings, there would be about 780KB overhead, which is something I wouldn't worry about unless you are in an environment with strict memory limitations.
In case the length of the string is fixed or varies in minimal way (let's say 2 to 4 characters), then it could be more reasonable to use an array with automatic storage duration:
struct X {
...
char code[4]; // up to 4 characters
};
which would work fine even while copying instances of it in a following way:
X x1, x2;
...
x2 = x1;
However in case you don't have a really good reason to worry about this right now, anything you'd do at this point is pretty much a premature optimization.
Upvotes: 0
Reputation:
If your goal is to create a hash table, you should try to eliminate any distractions that would make that specific task more complicated. As such you should use std::string for the mutable values in your table so you don't have to spend development effort on allocating and deallocating char*
Once your hash table is functional and correct, if you have a reason to move to char*, then you can always change to that later on. Focus on your highest priority goal, the hash table, and don't spend time on trying to beat std::string performance until your first goal is reached; beating std::string may not be worthwhile in any case.
Upvotes: 0
Reputation: 1753
I'll assume you are trying to implement unordered_map (H.W?) and that this is why you dont use it.
you should use std::vector, or std::string, but don't use the array.
And why is there problem of std::string using a stack?
Upvotes: 1