总结目录
1 用了自定义struct来作为map的key_val
2 重新理解了比较器的写法,对于为什么要求写一个严格小于的比较器有了理解。
3 比较器的默认返回是true,我们应该写成false
1 自定义struct来作为map的key_val
map<node, int, cmp> mp;
其中
struct cmp {
bool operator()(node obj1, node obj2)const {....}
是比较器
2 为什么要求写一个严格小于的比较器
写一个严格小于的比较器,可以用于判断是严格小于,严格大于,还是等于。比如如果a<b return false && a>b return false;说明 a == b;严格相等!
3 比较器的默认返回是true,我们应该写成false
一开始的代码中,在cmp的最后没有return false,导致搜索相同的值的时候,即mp.count(一个已经存在的值)的时候,会发生报错,原因是因为比较器返回了true,但是不存在这种情况,因为应该是严格小于,如果相等要返回false,因此后面加上了 return false才成立了。
测试代码
#include<iostream>
#include<map>
using namespace std;
struct node {
int x;
int y;
int step;
};
struct cmp {
bool operator()(node obj1, node obj2)const {
//这里,我需要写一个严格的小于程序,才能保证后面两次取反是完全相等的
//返回true说明是严格小于的,非严格小于就返回false
if (obj1.x != obj2.x) {
return obj1.x < obj2.x;
}
else if (obj1.y != obj2.y) {
return obj1.y < obj2.y;
}
else if (obj1.step != obj2.step) {
return obj1.step < obj2.step;
}
else
return false;
}
};
map<node, int, cmp> mp;
bool f(int a,int b) {
if (a != b) {
return a < b;
}
else {
return false;
}
}
int main() {
bool test = false;
if (test == f(1,1)) {
cout << "默认是false"<<endl;
}
else {
cout << "默认是true"<<endl;
}
cout << mp.size() << endl;
node tmp;
tmp.x = 1;
tmp.y = 2;
tmp.step = 1;
if (mp.count(tmp) == 0) {
mp[tmp] = 1;
}
cout << mp.size() << endl;
tmp.x = 1;
tmp.y = 2;
tmp.step = 1;
if (mp.count(tmp) == 0) {
mp[tmp] = 1;
}
cout << mp.size() << endl;
tmp.x = 2;
tmp.y = 4;
tmp.step = 1;
if (mp.count(tmp) == 0) {
mp[tmp] = 1;
}
cout << mp.size() << endl;
tmp.x = 1;
tmp.y = 2;
tmp.step = 3;
if (mp.count(tmp) == 0) {
mp[tmp] = 1;
}
cout << mp.size() << endl;
return 0;
}