How can I make the map::find operation case insensitive?

前端 未结 11 1877
野的像风
野的像风 2020-12-01 00:23

Does the map::find method support case insensitive search? I have a map as follows:

map > directory;
<         


        
11条回答
  •  情歌与酒
    2020-12-01 00:26

    I'd like to present a short solution without using Boost or templates. Since C++11 you can also provide a lambda expression as custom comparator to your map. For a POSIX-compatible system, the solution could look as follows:

    auto comp = [](const std::string& s1, const std::string& s2) {
        return strcasecmp(s1.c_str(), s2.c_str()) < 0;
    };
    std::map, decltype(comp)> directory(comp);
    

    Code on Ideone

    For Window, strcasecmp() does not exist, but you can use _stricmp() instead:

    auto comp = [](const std::string& s1, const std::string& s2) {
        return _stricmp(s1.c_str(), s2.c_str()) < 0;
    };
    std::map, decltype(comp)> directory(comp);
    

    Note: Depending on your system and whether you have to support Unicode or not, you might need to compare strings in a different way. This Q&A gives a good start.

提交回复
热议问题