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;
}