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

来源:互联网 发布:淘宝视频下载专用工具 编辑:程序博客网 时间:2024/06/05 16:50

http://blog.csdn.net/liang5630/article/details/9768703


C++的容器大多数都是自动排序的,所以你使用这些容器时,你加入的元素类型必须是可以比较大小的,如果不是,则需要自定义排序规则,例如你自定义的结构体:

[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <set>  
  3. using namespace std;  
  4. struct ju  
  5. {  
  6.     int id,x,y;  
  7.     bool operator <(const ju &a)const //排序并且去重复  
  8.     {  
  9.         if(id==a.id)  
  10.         {  
  11.             if(x==a.x) return y<a.y;  
  12.             else return x<a.x;  
  13.         }  
  14.         else return id<a.id;  
  15.     }  
  16. }tt;  
  17. set<ju> my;   
  18. set<ju> ::iterator it;   
  19. int main(int argc, char *argv[])  
  20. {  
  21.     int t,n,i,j;  
  22.     cin>>t;  
  23.     while(t--)  
  24.     {  
  25.         cin>>n; my.clear();  
  26.         for(i=0;i<n;i++)  
  27.         {  
  28.             cin>>tt.id>>tt.x>>tt.y;  
  29.             if(tt.x<tt.y) swap(tt.x,tt.y);  
  30.             my.insert(tt);  
  31.         }     
  32.         for(it=my.begin();it!=my.end();it++)  
  33.             cout<<(*it).id<<" "<<(*it).x<<" "<<(*it).y<<endl;  
  34.     }  
  35.     return 0;  


0 0