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

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

    In case you don't want to touch the map type (to keep it's original simplicity and efficiency), but don't mind using a slower case-insensitive find function (O(N)):

    string to_lower(string s) {
        transform(s.begin(), s.end(), s.begin(), (int(*)(int)) tolower );
        return s;
    }
    
    typedef map map_type;
    
    struct key_lcase_equal {
        string lcs;
        key_lcase_equal(const string& s) : lcs(to_lower(s)) {}
        bool operator()(const map_type::value_type& p) const {
            return to_lower(p.first) == lcs;
        }
    };
    
    map_type::iterator find_ignore_case(map_type& m, const string& s) {
        return find_if(m.begin(), m.end(), key_lcase_equal(s));
    }
    

    PS: Maybe it was Roger Pate's idea, but not sure, since some details were a bit off (std::search?, direct string comparator?)

提交回复
热议问题