Home > Software engineering >  std::set custom string comparison using boost::iequals
std::set custom string comparison using boost::iequals

Time:03-03

Following code works well without issues but wondering, if it is possible to rewrite custom comparison operator using boost::iequals , which compares without converting to upper.

std::string copyToUpper(std::string s)
{
    std::transform(s.begin(),s.end(),s.begin(),::toupper);
    return s;   
}

struct caseInsensitiveCompare {
    bool operator() (const std::string& a, const std::string& b) const {
        return (copyToUpper(a).compare(copyToUpper(b)) < 0);
    }
};
std::set<std::string, caseInsensitiveCompare> keys;

CodePudding user response:

Almost all STL containers rely on strict weak ordering. So the comparison function needs to return, not whether the strings are equal to each other, but that one is "less" than the other. But boost::iequals checks for equality and not if one string is "less" than the other, so you can't use it for the comparator of a map, a set or a sort function.

  • Related