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

前端 未结 11 1878
野的像风
野的像风 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:31

    Here are some other alternatives, including one which performs significantly faster.

    #include    
    #include    
    #include    
    #include    
    #include    
    
    using std::string;
    using std::map;
    using std::cout;
    using std::endl;
    
    using namespace boost::algorithm;
    
    // recommended in Meyers, Effective STL when internationalization and embedded
    // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
    struct ciLessLibC : public std::binary_function {
        bool operator()(const string &lhs, const string &rhs) const {
            return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ;
        }
    };
    
    // Modification of Manuel's answer
    struct ciLessBoost : std::binary_function
    {
        bool operator() (const std::string & s1, const std::string & s2) const {
            return lexicographical_compare(s1, s2, is_iless());
        }
    };
    
    typedef map< string, int, ciLessLibC> mapLibc_t;
    typedef map< string, int, ciLessBoost> mapBoost_t;
    
    int main(void) {
        mapBoost_t cisMap; // change to test other comparitor 
    
        cisMap["foo"] = 1;
        cisMap["FOO"] = 2;
    
        cisMap["bar"] = 3;
        cisMap["BAR"] = 4;
    
        cisMap["baz"] = 5;
        cisMap["BAZ"] = 6;
    
        cout << "foo == " << cisMap["foo"] << endl;
        cout << "bar == " << cisMap["bar"] << endl;
        cout << "baz == " << cisMap["baz"] << endl;
    
        return 0;
    }
    

提交回复
热议问题