c_cpp STL_sort_rank
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp STL_sort_rank相关的知识,希望对你有一定的参考价值。
int arr[] = {73, 68, 80, 85, 73, 74, 33, 49, 74, 90, 23, 22, 1, 0, 57, 11, 27, 35, 60, 45};
int len = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr+len, compare);
// SET the purpose condition.
bool compare(int front, int end) {
return front > end; // DESC
return front < end; // ASC
}
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int NUM = 20;
typedef struct {
char ID[20];
int grade;
int rank;
} Stu;
bool cmp(Stu a, Stu b);
int main()
{
int arr[NUM] = {73, 68, 80, 85, 73, 74, 33, 49, 74, 90, 23, 22, 1, 0, 57, 11, 27, 35, 60, 45};
Stu stu[NUM];
for(int i = 0; i < NUM; i++) {
sprintf(stu[i].ID, "Std_NO.%03d", i+1);
stu[i].grade = arr[i];
}
// Ranking RULES: same grade for same rank
sort(stu, stu+NUM, cmp);
// * init
int duplicate_num = 0;
stu[0].rank = 1;
for(int i = 1; i < NUM; i++) {
if(stu[i].grade == stu[i-1].grade) {
stu[i].rank = stu[i-1].rank;
duplicate_num ++;
} else {
stu[i].rank = stu[i-1].rank + 1 + duplicate_num; // Next
duplicate_num = 0; // RE-init
}
}
for(int i = 0; i < NUM; i++) {
printf("No: %2d | ID: %s | Grades: %2d | Rank: %d\n", i+1, stu[i].ID, stu[i].grade, stu[i].rank);
}
return 0;
}
// as front.grade > later.grade ORDER
bool cmp(Stu a, Stu b) {
return a.grade > b.grade;
}
以上是关于c_cpp STL_sort_rank的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp 200.岛屿数量
c_cpp 127.单词阶梯
c_cpp MOFSET
c_cpp MOFSET
c_cpp 31.下一个排列
c_cpp string→char *