严格弱排序

严格弱排序:如果x<y为true,那么!(y<x)为true,可以理解为俩个数据正序逆序传入比较函数中,得到的结果需要一致

如果需要给map自定义key,那么key要支持operator<,并且operator<是严格弱排序的,如果不是严格弱排序,结果是未定义的(可能死循环,可能值被覆盖,windows和linux各种编译器版本之间也不一致)

如下程序中如果使用了错误的比较大小的方法,则在赋值时会崩溃,因为map在赋值或插入后会进行排序,当俩个数在比较的过程中,没有严格保证大小,则会导致崩溃

struct SKey
{
	SKey(int a, int b, int c)
		:m_a(a), m_b(b), m_c(c)
	{
	}
	int m_a;
	int m_b;
	int m_c;
};

//正确的比较大小的方法
struct Skey_Right_Cmp
{
	bool operator()(const SKey& left, const SKey& right) const
	{
		if (left.m_a < right.m_a)
			return true;
		else if (left.m_a > right.m_a)
			return false;
		if (left.m_b < right.m_b)
			return true;
		else if (left.m_b > right.m_b)
			return false;
		return left.m_c < right.m_c;
	}
};

//错误的比较大小的方法
struct Skey_Wrong_Cmp
{
	bool operator()(const SKey& left, const SKey& right) const
	{
		if (left.m_a < right.m_a)
			return true;
		if (left.m_b < right.m_b)
			return true;
		if (left.m_c < right.m_c)
			return true;
		return false;
	}
};

//插入和删除测试,用错误的比较函数在执行map.erase时
//在gcc 4.1上可能导致死循环

template<typename KeyCmp>
void erase_test()
{
	std::map<SKey, int, KeyCmp>data;
	for (int i = 0; i < 10; ++i)
		for (int j = 0; j < 10; ++j)
			for (int k = 0; k < 10; ++k)
				data[SKey(i, j, k)] = 0;
	assert(data.size() == 1000);
	for (int i = 0; i < 1000; ++i)
	{
		std::cout << "erase" << i << "\n";
		data.erase(SKey(std::rand() % 10, std::rand() % 10, std::rand() % 10));
	}
}
	
int main()
{
	std::cout << "begin right test....\n";
	erase_test<Skey_Right_Cmp>();
	std::cout << "begin wrong test....\n";
	erase_test<Skey_Wrong_Cmp>();
	std::cout << "test end" << std::endl;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值