c++ map where keys are strings

Started by
10 comments, last by bulgurmayo 16 years, 9 months ago
In C++, what is the best way to create a map where keys are strings. Should I go for a std::map<std ::string, MyObject>, Or should I better use a std::map<const char*, MyObject> I know that char* are evil, but by using the first version I am afraid of costly string copies anytime the map is modified.
Advertisement
use strings, its not that costly vs the pain in the ass you will run into having to create a new char * each time you add an entry, also you will have to remeber to delete map::iter->first to clean up those allocated char *'s
Additionally to the pain std::map<const char*, MyObject> will not work as you think it would.

The map will use the actual pointer values for the sorting. It will also not be able to know that two char* strings containing the same text are the same if they are located at different addresses.

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

This I knew, I was meant this :

class LessFctr {
public:
bool operator () ( const char* s1, const char* s2) const {return strcmp(s1, s2) < 0;}
};
std::map<const char*, MyObject, LessFctr>
Why aren't the string copies so costly ?
Isn't a whole copy going to take place everytime ?
Quote:Original post by bulgurmayo
Why aren't the string copies so costly ?
Isn't a whole copy going to take place everytime ?


Depends. If your library uses a Copy-On-Write optimization for its strings, then actual data copies only happen when you modify a string. Even if the strings are copies, short strings (less than 16 characters) are copied near-instantly anyway on most implementations, without even a memory allocation.

Besides, unless your program revolves entirely about manipulating the strings in this map for several minutes, I wouldn't worry about this, as the difference in performance will most likely be on the hundred-nanosecond-per-second scale.
Thanks for your answer
More importantly, copying around will only happen when the map contents are modified, i.e. when things are added (when they're removed, the map will simply reorganize "map nodes" in memory, which is a bunch of pointer manipulation, but no changes to the keys or copying of data). In normal use, you spend much, much more time looking things up in a map than you do on creating it, so the creation efficiency doesn't matter much.
char * is exactly the same as std::string.

Except, like in soap operas, char * is the evil twin of the good doctor, the std::string.

The cost of lookup would be exactly the same in both cases, namely full string vs. string comparison.
and string comparisons might even be faster, as a string knows its length

This topic is closed to new replies.

Advertisement