STL set容器添加结构体并排序

 1 #include <iostream> 
 2 #include <string>
 3 #include <cstring>  //strcpy
 4 #include <cstdlib>  //malloc
 5 #include <cstdio>  //printf
 6 #include <set>
 7 
 8 struct Node{
 9     Node(int w, int i):weight(w),index(i){}
10     int weight;
11     int index;
12     bool operator<(const Node& nptr) const{
13         return nptr.weight < this->weight || (nptr.weight == this->weight && nptr.index < this->index);
14     }
15 };
16 using namespace std;
17 
18 int main(){
19     set<Node> s;
20     int w,i;
21     while(cin>>w>>i){
22         s.insert(Node(w,i));
23     }
24     set<Node>::iterator it;
25     for(it = s.begin(); it != s.end(); it++){
26         cout<<(*it).weight<<" "<<(*it).index<<endl;
27     }
28 
29     return 0;
30 }

输入:

1 2
1 3
1 4
2 4
3 5
1 5
1 2
输出:

3 5
2 4
1 5
1 4
1 3
1 2
分析:可以看到最后一组{1 2}插入失败,其余元素按照降序排列

转载于:https://www.cnblogs.com/hu983/p/5354941.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值