set自定义去重有两种方法(map也类似):
1,重载<比较符
将set的元素类型如struct Node中的operator <()函数重载,保证对相同的元素始终返回false即可,示例代码如下:
#include <iostream>
#include <set>
using namespace std;
struct Node{
int id,value;
Node(){}
Node(int _id,int _value):id(_id),value(_value){}
bool operator < (const Node& b)const {
if(id == b.id)return false;//去重
//降序
if(value != b.value)return value > b.value;
else return id > b.id;
}
};
int main(){
set<Node> S;
S.insert(Node(1,2));
S.insert(Node(2,3));
S.insert(Node(2,4));//插入失败
S.insert(Node(3,4));
for(auto it=S.begin() ; it!=S.end() ; ++it)
printf("id:%d value:%d\n",(*it).id,(*it).value);
return 0;
}
2,重载( )运算符
新建一个MyComparator类,在该类中重载( )运算符函数,保证对相同的目标元素类型始终返回false,之后在初始化新的该set时于<>内加上该类,如set<Node, MyComparator>即可,示例代码如下:
#include <iostream>
#include <set>
using namespace std;
struct Node{
int id,value;
Node(){}
Node(int _id,int _value):id(_id),value(_value){}
/*
bool operator < (const Node& b)const {
if(id == b.id)return false;//去重
//降序
if(value != b.value)return value > b.value;
else return id > b.id;
}
*/
};
struct MyComparator{
bool operator() (struct Node a, struct Node b){
if(a.id == b.id)return false;//去重
//降序
if(a.value != b.value)return a.value > b.value;
else return a.id > b.id;
}
};
int main(){
set<Node, MyComparator> S;
S.insert(Node(1,2));
S.insert(Node(2,3));
S.insert(Node(2,4));//插入失败
S.insert(Node(3,4));
for(auto it=S.begin() ; it!=S.end() ; ++it)
printf("id:%d value:%d\n",(*it).id,(*it).value);
return 0;
}
可知第二种方法更具通用性,可以创建多个不同的Comparator类以满足不同的比较要求。