栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ STL set的自定义去重

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ STL set的自定义去重

set自定义去重有两种方法(map也类似):

1,重载<比较符

将set的元素类型如struct Node中的operator <()函数重载,保证对相同的元素始终返回false即可,示例代码如下:

#include 
#include  
 
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 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:%dn",(*it).id,(*it).value);
	return 0;
}
2,重载( )运算符

新建一个MyComparator类,在该类中重载( )运算符函数,保证对相同的目标元素类型始终返回false,之后在初始化新的该set时于<>内加上该类,如set即可,示例代码如下:

#include 
#include  
 
using namespace std;
 
struct Node{
	int id,value;
	Node(){}
	Node(int _id,int _value):id(_id),value(_value){}
	
};

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 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:%dn",(*it).id,(*it).value);
	return 0;
}

可知第二种方法更具通用性,可以创建多个不同的Comparator类以满足不同的比较要求。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/835766.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号