不区分大小写的std ::字符串集

cpx*_*cpx 20 c++ stl

你如何在std :: set中进行不区分大小写的插入或搜索字符串?

例如-

std::set<std::string> s;
s.insert("Hello");
s.insert("HELLO"); //not allowed, string already exists.
Run Code Online (Sandbox Code Playgroud)

ybu*_*ill 35

您需要定义自定义比较器:

struct InsensitiveCompare { 
    bool operator() (const std::string& a, const std::string& b) const {
        return stricmp(a.c_str(), b.c_str()) < 0;
    }
};

std::set<std::string, InsensitiveCompare> s;
Run Code Online (Sandbox Code Playgroud)

  • 当我阅读InsensitiveCompare时,我忍不住想起了我的岳母.+1. (14认同)
  • 如果字符串中有NUL字符,则此方法无法正常工作.见[this question](/sf/ask/814481/). (2认同)