记忆化搜索的map使用:将自定义struct作为map的key_val

总结目录

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值