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

时间:2022-09-03 19:11:14
 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}插入失败,其余元素按照降序排列