STL:set中使用自定义比较操作

    set关联容器对关键字类型有一些限制,关键字类型必须定义比较操作,默认情况下,标准库使用关键字类型的<运算符来比较两个关键字。当关键字类型是用户自定义类型时,为了容器中关键字类型正确,我们有三种方式提供正确的关键字类型。
    第一中方式:在关键字类型中对<运算符进行重载。假设关键字类型为Node,Node中有两个成员变量,我们按照第一个成员变量start进行比较。我们定义一个成员函数:bool operator<(const Node& other) const。代码如下:
#include<iostream>
#include<set>
using namespace std;

class Node
{
public:
	int start;
	int end;
	Node(){}
	Node(int s, int e) :start(s), end(e)
	{
	
	}
	bool operator<(const Node &other) const
	{
		return start < other.start;
	}
};
int main(void)
{
	multiset<Node> m;
	m.insert(Node(4, 5));
	m.insert(Node(3, 4));
	m.insert(Node(6, 7));
	system("pause");
	return 0;
}

第二种方式:使用重载函数调用运算符类型的对象进行比较操作。代码如下:
#include<iostream>
#include<set>
using namespace std;

class Node
{
public:
	int start;
	int end;
	Node(){}
	Node(int s, int e) :start(s), end(e)
	{
	
	}
};

class CompareClassNode
{
public:
	bool operator()(const Node &lhs, const Node &rhs)
	{
		return lhs.start < rhs.start;
	}
};

int main(void)
{
	multiset<Node,CompareClassNode> m;
	m.insert(Node(4, 5));
	m.insert(Node(3, 4));
	m.insert(Node(6, 7));
	system("pause");
	return 0;
}

第三中方式:使用自定义比较函数。必须这样定义multiset<Node, decltype(compareNode)*> m(compareNode)。代码如下:
#include<iostream>
#include<set>

using namespace std;

class Node
{
public:
	int start;
	int end;
	Node(){}
	Node(int s, int e) :start(s), end(e)
	{
	
	}
};

bool compareNode(const Node &lhs,const Node &rhs)
{
	return lhs.start < rhs.start;
}


int main(void)
{
	multiset<Node, decltype(compareNode)*> m(compareNode);
	m.insert(Node(4, 5));
	m.insert(Node(3, 4));
	m.insert(Node(6, 7));
	system("pause");
	return 0;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值