c++ map where keys are strings
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.
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.
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.
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>
class LessFctr {
public:
bool operator () ( const char* s1, const char* s2) const {return strcmp(s1, s2) < 0;}
};
std::map<const char*, MyObject, LessFctr>
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.
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement