C++学习之路: 优先级队列使用模板(防止忘记)

当优先级队列中存放我们自定义规则时, 编译器不知道该如何排序

如: priority_queue<Person> 这种代码是无法通过编译的, 需要我们手动写一个比较规则

priority_queue<Person, comp> 即可

代码如下

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <queue>
 5 #include <fstream>
 6 #include <stdexcept>
 7 using namespace std;
 8 
 9 struct Score
10 {
11     int id_;
12     string name_;
13     int score_;
14 
15     Score(int id, const string &name, int score)
16         :id_(id), name_(name), score_(score)
17     { }
18 };
19 
20 class Comp
21 {
22 public:
23     bool operator() (const Score &s1, const Score &s2)
24     {
25         if(s1.score_ != s2.score_)
26             return s1.score_ < s2.score_;
27         if(s1.name_ != s2.name_)
28             return s1.name_ > s2.name_;
29         return s1.id_ > s2.id_;
30     } 
31 };
32 
33 typedef priority_queue<Score, vector<Score>, Comp> ScoreList;
34 
35 void readFile(const string &filename, ScoreList &scores);
36 void printScoreList(ScoreList &scores);
37 
38 int main(int argc, char const *argv[])
39 {
40     ScoreList scores;
41 
42     readFile("score.txt", scores);
43     printScoreList(scores);
44 }
45 
46 void readFile(const string &filename, ScoreList &scores)
47 {
48     ifstream in(filename.c_str());
49     if(!in)
50         throw runtime_error("文件打开失败");
51 
52     string line;
53     while(getline(in, line))
54     {
55         int id;
56         char name[20] = {0};
57         int score;
58         sscanf(line.c_str(), "%d %s %d", &id, name, &score);
59         scores.push(Score(id, name, score));
60     }
61 
62     in.close();
63 }
64 
65 void printScoreList(ScoreList &scores)
66 {
67     while(!scores.empty())
68     {
69         Score s = scores.top();
70         scores.pop();
71         cout << "id = " << s.id_ << " name = " << s.name_ << " score = " << s.score_ << endl;
72     }
73 }

上例是一个很简单的成绩单排序。 只需简单的写一个排序规则类, 重载一下排序类的()函数调用符号就行了。

此代码用于忘记时复习

原文地址:https://www.cnblogs.com/DLzhang/p/4047232.html