如何使 STL::Map 键不区分大小写
how to make stl::map key case insensitive
我是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;
编辑:如果您无法使用stricmp
或strcasecmp
请使用:
#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 的一部分 - 但无论哪种方式都很容易编写。
相关文章:
- 使字母检查不区分大小写
- 如何执行不区分大小写的字符串比较?
- CMake 添加不区分大小写的源文件
- 提升program_option配置文件的不区分大小写的解析
- 如何提升Perl正则表达式匹配,支持区分大小写/不区分大小写
- 对字符串向量进行排序,但不区分大小写
- 比较最后一个字符,不区分大小写(带谓词?
- 在字符串的 boost::unordered_set 中使用 Lambda 函数 - 不区分大小写
- 为什么不区分大小写适用于 std::unordered_set的 std::hash 函数?
- 如何使字符串中的每个字母不区分大小写
- 不区分大小写的字符串
- 使 strcmp() 不区分大小写而不使用 strcmpi() (C++)
- 是否有函数/WinAPI 可以判断一个字符串是否以不区分大小写的语言方式以另一个字符串开头?
- 极快的is_iequal?(不区分大小写的相等比较)
- C++,检查两个字符串的不区分大小写相等
- 在字符串向量中查找字符串,不区分大小写的c++
- 如何在C++中实现unicode不区分大小写的比较
- 不区分大小写的操作
- ICU:创建不区分大小写的排序规则
- 内置C++函数,使两个字符串的比较不区分大小写