使map :: find操作大小写不敏感 [英] Making map::find operation case insensitive

查看:214
本文介绍了使map :: find操作大小写不敏感的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

map :: find方法是否支持不区分大小写的搜索?

我有一个如下的地图

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

map<string,vector<string> > directory;  

,并希望以下搜索忽略大小写。

and want the below search to ignore case.

directory.find(search_string);


推荐答案

它没有默认。您将必须提供一个自定义比较器作为第三个参数。以下代码段将帮助您...

It does not by default. You will have to provide a custom comparator as a third argument. Following snippet will help you...

  /************************************************************************/
  /* Comparator for case-insensitive comparison in STL assos. containers  */
  /************************************************************************/
  struct ci_less : std::binary_function<std::string, std::string, bool>
  {
    // case-independent (ci) compare_less binary function
    struct nocase_compare : public std::binary_function<unsigned char,unsigned char,bool> 
    {
      bool operator() (const unsigned char& c1, const unsigned char& c2) const {
          return tolower (c1) < tolower (c2); 
      }
    };
    bool operator() (const std::string & s1, const std::string & s2) const {
      return std::lexicographical_compare 
        (s1.begin (), s1.end (),   // source range
        s2.begin (), s2.end (),   // dest range
        nocase_compare ());  // comparison
    }
  };

std :: map< std :: string,std :: vector< std :: string>,ci_less> myMap;

注意:std :: lexicographical_compare有一些细节细节。如果您考虑区域设置,字符串比较并不总是直接的。如果有兴趣,请参阅这个线程clc ++。

NOTE: std::lexicographical_compare has some nitty-gritty details. String comparison isn't always straightforward if you consider locales. See this thread on c.l.c++ if interested.

这篇关于使map :: find操作大小写不敏感的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆