您的位置:首页 > 其它

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

2016-04-05 14:26 489 查看
#include <iostream>
#include <string>
#include <cstring>  //strcpy
#include <cstdlib>  //malloc
#include <cstdio>  //printf
#include <set>

struct Node{
Node(int w, int i):weight(w),index(i){}
int weight;
int index;
bool operator<(const Node& nptr) const{
return nptr.weight < this->weight || (nptr.weight == this->weight && nptr.index < this->index);
}
};
using namespace std;

int main(){
set<Node> s;
int w,i;
while(cin>>w>>i){
s.insert(Node(w,i));
}
set<Node>::iterator it;
for(it = s.begin(); it != s.end(); it++){
cout<<(*it).weight<<" "<<(*it).index<<endl;
}

return 0;
}


输入:

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}插入失败,其余元素按照降序排列
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: