/* 题目:实现多条件按优先级进行排序
* 对一个item进行多条件排序,排序有优先级,startTime > duration > type,
* 意思就是startTime大的优先,startTime相同则看duration,依次类推。
* 补充:
* sort函数的第三个传入的参数类型和需要排序的数据类型一致,如果认为第一个参数比第二个小,
* 也就是第一个参数需要排在第二个参数前面时返回true,反之返回 false。系统默认a<b时返回true,于是从小到大排,升序。
*/
#include<iostream>
#include<unordered_map>
#include<vector>
#include<algorithm>
using namespace std;
struct MusicInfo {
int startTime;
int duration;
int type;
};
typedef pair<int, MusicInfo> PAIR;
vector<int> SortMusic(unordered_map<int, MusicInfo> player)
{
vector<PAIR> order(player.begin(), player.end());
// 利用lambda表达式进排序
sort(order.begin(), order.end(), [](PAIR &p1, PAIR &p2) {
if(p1.second.startTime < p2.second.startTime) { // 优先级1:开始时间
return true;
} else if (p1.second.startTime > p2.second.startTime) {
return false;
} else { // 优先级1:开始时间一样
if (p1.second.duration < p2.second.duration) { // 优先级2:持续时间
return true;
} else if(p1.second.duration > p2.second.duration) {
return false;
} else { // 优先级2:持续时间一样
if (p1.second.type < p2.second.type) { // 优先级3:类型
return true;
} else {
return false;
}
}
}
});
vector<int> res;
for(int loop = 0; loop < order.size(); loop++) {
cout << "key_id" << ":" << order[loop].first << endl;
res.push_back(order[loop].first);
}
return res;
}
int main()
{
unordered_map<int, MusicInfo> player;
MusicInfo item1 = {1, 3,3};
MusicInfo item2 = {1,2,2};
MusicInfo item3 = {2,2,1};
player[1] = item1;
player[2] = item2;
player[3] = item3;
SortMusic(player);
return 0;
}