C++:map自定义比较函数
map容器可以自定义键比较函数。
例如,对某个map对象操作,键比较都忽略大小写,如下:
main.C
#include <iostream>
#include <map>
#include <strings.h>
#include <algorithm>
using namespace std;
// 比较函数
struct MyCmp {
bool operator()(string l, string r) const { return strcasecmp(l.c_str(), r.c_str()) < 0; }
};
int main() {
map<string, int, MyCmp> mymap;
mymap["key"] = 0;
map<string, int, MyCmp>::iterator myit = mymap.find("KEY");
if (myit != mymap.end()) {
cout << "found!" << endl;
} else {
cout << "not found!" << endl;
}
return 0;
}
编译 & 运行:
[test1280@localhost ~]$ g++ -o main main.C
[test1280@localhost ~]$ ./main
found!
在创建map对象时:
- 第一个string指明键类型;
- 第二个int指明值类型;
- 第三个MyCmp是个比较函数,指明“什么样的两个键等价”;
比较函数实现中用strcasecmp忽略大小写比较,因此,对设置了比较函数为MyCmp的map对象操作,“key"等价于"KEY”,也等价于"Key"…
注意,比较函数返回一个bool类型的结果,即对两个键进行比较,结果必定是true或者false。
如果,compare(key1, key2)返回false并且compare(key2, key1)返回false,则key1等价于key2。
踩过的坑!
main.C
#include <iostream>
#include <map>
#include <strings.h>
#include <algorithm>
using namespace std;
// 比较函数
struct MyCmp {
bool operator()(const char *l, const char *r) const { return strcasecmp(l, r) < 0; }
};
map<const char *, int, MyCmp> g_mymap;
void setKV() {
// 栈上对象
string key1 = "key";
g_mymap[key1.c_str()] = 1;
}
int main() {
setKV();
//string key2("XXX");
string key3("KEY");
map<const char *, int, MyCmp>::iterator myit = g_mymap.find(key3.c_str());
if (myit != g_mymap.end()) {
cout << "found!" << endl;
} else {
cout << "not found!" << endl;
}
return 0;
}
编译 & 运行(在你的环境下执行,并不总是如下结果噢!):
[test1280@localhost ~]$ g++ -o main main.C
[test1280@localhost ~]$ ./main
found!
如果去掉key2那一行的注释,重新编译并运行:
[test1280@localhost ~]$ g++ -o main main.C
[test1280@localhost ~]$ ./main
not found!
当设置了比较函数并且使用指针作为map的键类型需特别留意:键地址无效/非法。
g_mymap的键类型是const char *,是指针类型。
setKV函数给map对象增加了一对key-value,但是这里的key1是一个栈上对象,保存到map中的键是一个栈上的地址值。
当函数调用完成,栈空间释放,g_mymap中的key实际指向的是一个非法地址/无效地址。
此时再次比较查找key3等价于key1(非法地址/无效地址),“not found”是常态,"found"才是偶然。