0
点赞
收藏
分享

微信扫一扫

C++ set 多级排序 多维度排序

小a草 2022-02-11 阅读 67


#include <iostream>
#include <set>
#include <algorithm>
using namespace std;

/*Student结构体*/
struct Student {
string name;
int id;
int score;
};

/*“仿函数"。为Student set指定排序准则*/
class studentSortCriterion {
public:
/*类型要与set容器类型一致*/
bool operator()( const Student *a, const Student *b ) const
{
// 成绩相等,按照id从小到大排;成绩不相等,按照成绩从大到小排
return( (a->score == b->score) ? (a->id < b->id) : (a->score > b->score) );
}
};


int main()
{
set<Student*, studentSortCriterion> stuSet;
set<Student*> stus;

Student stu1, stu2, stu3;
stu1.name = "张三";
stu1.id = 1;
stu1.score = 100;

stu2.name = "李四";
stu2.id = 2;
stu2.score = 90;

stu3.name = "小明";
stu3.id = 3;
stu3.score = 100;

stuSet.insert( &stu1 );
stuSet.insert( &stu2 );
stuSet.insert( &stu3 );

/* 查找 */
Student stuTem;
stuTem.score = 100;
stuTem.id = 3;
Student * stuTempPtr;
set<Student*, studentSortCriterion>::iterator iter;
iter = stuSet.find( &stuTem );
if ( iter != stuSet.end() )
{
cout << (*iter)->name << endl;
}

else {
cout << "Cannot find the student!" << endl;
}


/* 遍历 */
for ( std::set<Student*, studentSortCriterion>::iterator it = stuSet.begin(); it != stuSet.end(); it++ )
{
std::cout << (*it)->name << endl;
}
}

上面程序会根据学生ID先进行排名然后再根据分数进行排名,排序准则需要满足以下要求,摘自C++标准库第二版:

C++ set 多级排序 多维度排序_ios

输出结果:

C++ set 多级排序 多维度排序_ios_02


​​c++ set容器排序准则 - 每天一点积累 - 博客园​​


举报

相关推荐

0 条评论