How can I make the map::find operation case insensitive?(如何使 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::lexicographical_compare 有一些细节.如果您考虑语言环境,字符串比较并不总是那么简单.如果有兴趣,请参阅 clc++ 上的 this 线程.
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.
更新:在 C++11 中 std::binary_function 已被弃用,因为类型是自动推导出来的,所以没有必要.
UPDATE: With C++11 std::binary_function is deprecated and is unnecessary as the types are deduced automatically.
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
}
};
这篇关于如何使 map::find 操作不区分大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使 map::find 操作不区分大小写?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
