当前位置:编程学习 > C/C++ >>

C++ set自定义排序规则(nyist 8)

C++的容器大多数都是自动排序的,所以你使用这些容器时,你加入的元素类型必须是可以比较大小的,如果不是,则需要自定义排序规则,例如你自定义的结构体:
#include <iostream>
#include <set>
using namespace std;
struct ju
{
	int id,x,y;
	bool operator <(const ju &a)const //排序并且去重复
	{
		if(id==a.id)
		{
			if(x==a.x) return y<a.y;
			else return x<a.x;
		}
		else return id<a.id;
	}
}tt;
set<ju> my; 
set<ju> ::iterator it; 
int main(int argc, char *argv[])
{
	int t,n,i,j;
	cin>>t;
	while(t--)
	{
		cin>>n; my.clear();
		for(i=0;i<n;i++)
		{
			cin>>tt.id>>tt.x>>tt.y;
			if(tt.x<tt.y) swap(tt.x,tt.y);
			my.insert(tt);
		}	
		for(it=my.begin();it!=my.end();it++)
			cout<<(*it).id<<" "<<(*it).x<<" "<<(*it).y<<endl;
	}
	return 0;
}

 

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,