Let's assume I have a most straightforward std::set
of all:
std::set<std::string> my_set;
Now, I have a function which accepts const char*
and needs to tell me of this string exists or not in the set, implemented in the most straightforward way:
bool exists(const char* str) {
return my_set.count(str) > 0;
}
Now, this is obvious efficiency loss. A (potential) dynamic memory allocation followed by deallocation happens right here for no reason.
How can we eliminate that? I'd like to compare std::string
which I want to be the key type with char*
. One way would be to use unique_ptr<char>
instead of my key type with custom comparator, but that'd be super awkward.
The problem can be actually generalized to wider case, effectively, "how to invoke comparison with type provided without conversion to key type?"
P.S. I have seen std::string as map key and efficiency of map.find(), but I am not satisfied with the answer, which effectively reiterates that this optimization is not needed, while it is clearly wrong.