如何使 STL::Map 键不区分大小写

how to make stl::map key case insensitive

本文关键字:不区 大小写 Map 何使 STL      更新时间:2023-10-16

我是stl的新手。这是我下面的程序。

typedef pair<string, int> p;
int main(int argc, char *argv[])
{
  map<string,int> st;
  st.insert(p("hello",1));   //Inserted "hello" as key to map.
  st.insert(p("HELLO",1));   //Inserted "HELLO" as key to map. 
  cout<<"size="<<st.size()<<endl;    //Output is 2 because two records found "hello" and "HELLO"
  return 0;
}

我不想考虑重复的大小写更改(大写到小写单词,反之亦然)。这里 "st.insert(p("HELLO",1));" 应该失败,因此没有。的记录应为"1"而不是"2"。是否有任何标志设置或类似设置?

我无法找到相关问题,因此发布了这个问题。

任何帮助都是感激的。

使用自定义比较器:

struct comp { 
    bool operator() (const std::string& lhs, const std::string& rhs) const {
        return stricmp(lhs.c_str(), rhs.c_str()) < 0;
    }
};
std::map<std::string, int, comp> st;

编辑:如果您无法使用stricmpstrcasecmp请使用:

#include<algorithm>
//...
string tolower(string s) {
    std::transform(s.begin(), s.end(), s.begin(), ::tolower );
    return s;
}
struct comp { 
    bool operator() (const std::string& lhs, const std::string& rhs) const {
        return  tolower(lhs) < tolower(rhs);
    }
};
std::map<std::string, int, comp> st;

有两种方法可以做到这一点

首先 - 更改"比较"功能以忽略大小写

其次 - 每当您使用字符串从映射中放置或获取值时,请使用将其转换为小写的函数包装它。

首先,您需要做的就是创建一个"函数类"(带有operator()的类),该类接收两个字符串并返回左侧是否比右侧"小":

struct my_comparitor{
  bool operator()(const std::string &a, const std::string &b){
    // return iwhether a<b
  }
};
std::map<std::string,DATA_TYPE,my_comparitor> my_map;

对于第二个,只需这样做:

std::map<std::string,DATA_TYPE> my_map;
my_map.insert(std::make_pair(TO_LOWERCASE("hello"),1));
iter=my_map.find(TO_LOWERCASE(key));
cout << my_map[TO_LOWERCASE(name)];
// etc.

我不确定转换为小写的函数是否已经是 stl 的一部分 - 但无论哪种方式都很容易编写。