Say I have a std::set<std::string>
, and I wish to know whether it contains the string "name":
#include <string>
#include <set>
using namespace std;
bool has_name(const set<string> &s) {
return s.find("name") != s.end();
}
The above function constructs and destroys a temporary std::string with value "name". This inefficiency seems unnecessary, because std::string has facilities for comparing against const char* directly. I would like to eliminate this temporary.
I tried using a custom comparator with overloads:
struct str_comp_t {
bool operator()(const string &s1, const char *s2) const {
return s1.compare(s2) < 0;
}
bool operator()(const string &s1, const string &s2) const {
return s1.compare(s2) < 0;
}
};
typedef std::set<string, str_comp_t> string_set_t;
bool has_name_2(const string_set_t &s) {
return s.find("name") != s.end();
}
However only the variant taking std::string is called; the const char * is ignored.
How can I make this set compare against the constant string directly, instead of constructing an intermediate string?