49

map::find方法是否支持不区分大小写的搜索?我有一张地图如下:

map<string, vector<string> > directory;

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

directory.find(search_string);
4

11 回答 11

69

默认情况下它不会。您必须提供一个自定义比较器作为第三个参数。以下片段将帮助您...

  /************************************************************************/
  /* 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++ 上的此线程。

更新:不推荐使用 C++11 std::binary_function,因为类型是自动推导的,所以没有必要。

  struct ci_less
  {
    // case-independent (ci) compare_less binary function
    struct nocase_compare
    {
      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
    }
  };
于 2009-11-26T06:39:01.610 回答
23

这里有一些其他的替代方案,包括一个执行速度明显更快的替代方案。

#include    <map>
#include    <string>
#include    <cstring>
#include    <iostream>
#include    <boost/algorithm/string.hpp>

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<string, string, bool> {
    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<std::string, std::string, bool>
{
    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;
}
于 2010-06-09T20:45:44.297 回答
9

对于 C++11 及更高版本:

#include <strings.h>
#include <map>
#include <string>

namespace detail
{

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

}   // namespace detail


template <typename T>
using CaseInsensitiveMap = std::map<std::string, T, detail::CaseInsensitiveComparator>;



int main(int argc, char* argv[])
{
    CaseInsensitiveMap<int> m;

    m["one"] = 1;
    std::cout << m.at("ONE") << "\n";

    return 0;
}
于 2017-03-15T11:31:45.007 回答
6

std::map您可以使用三个参数进行实例化:键的类型、值的类型和比较函数——您喜欢的严格的弱排序(本质上,函数或函子的行为类似于operator<传递性和反反身性)。只需定义第三个参数来执行“不区分大小写的小于”(例如,通过<它正在比较的小写字符串上的 a),您将拥有您想要的“不区分大小写的映射”!

于 2009-11-26T06:39:43.590 回答
6

我使用以下内容:

bool str_iless(std::string const & a, 
               std::string const & b)
{
    return boost::algorithm::lexicographical_compare(a, b,  
                                                     boost::is_iless());
}
std::map<std::string, std::string, 
         boost::function<bool(std::string const &, 
                              std::string const &)> 
         > case_insensitive_map(&str_iless);
于 2010-01-06T09:05:14.540 回答
4

不,您不能这样做,find因为在这种情况下会有多个匹配项。例如,在插入时,您可以执行类似的操作map["A"] = 1map["a"] = 2并且现在如果您想要不区分大小写map.find("a"),那么预期的返回值是多少?解决此问题的最简单方法是仅在一种情况下(大写或小写)将字符串插入映射,然后在进行查找时使用相同的情况。

于 2009-11-26T06:36:45.187 回答
4

如果您不想触摸地图类型(以保持其原始的简单性和效率),但不介意使用较慢的不区分大小写的查找函数 (O(N)):

string to_lower(string s) {
    transform(s.begin(), s.end(), s.begin(), (int(*)(int)) tolower );
    return s;
}

typedef map<string, int> 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:也许这是 Roger Pate 的想法,但不确定,因为有些细节有点偏离(std::search?,直接字符串比较器?)

于 2009-11-26T17:29:03.530 回答
2

我想在不使用 Boost 或模板的情况下提出一个简短的解决方案。从C++11开始,您还可以提供lambda 表达式作为地图的自定义比较器。对于 POSIX 兼容的系统,解决方案可能如下所示:

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

Ideone 上的代码

对于 Window,strcasecmp()不存在,但您可以使用_stricmp()

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

注意:根据您的系统以及是否必须支持 Unicode,您可能需要以不同的方式比较字符串。本问答提供了一个良好的开端。

于 2019-03-15T14:12:15.553 回答
1

地图模板的 Compare 元素默认为二进制比较类“less”。看实现:

http://www.cplusplus.com/reference/std/functional/less/

您可能会创建自己的类,该类派生自 binary_function(父类到 less),并在不区分大小写的情况下进行相同的比较。

于 2009-11-26T06:37:09.617 回答
1

测试:

template<typename T>
struct ci_less:std::binary_function<T,T,bool>
  { bool operator() (const T& s1,const T& s2) const { return boost::ilexicographical_compare(s1,s2); }};

...

map<string,int,ci_less<string>> x=boost::assign::map_list_of
        ("One",1)
        ("Two",2)
        ("Three",3);

cout << x["one"] << x["TWO"] <<x["thrEE"] << endl;

//Output: 123
于 2013-06-27T15:00:11.960 回答
0

实现 std::less 函数并通过将两者更改为相同的情况进行比较。

于 2009-11-26T06:49:39.903 回答