When our custom rules are stored in the priority queue, the compiler does not know how to sort
such as: priority_queue<person> This code is not compiled, we need to manually write a comparison rule
Priority_queue<person, comp> can
The code is as follows
1#include <iostream>2#include <string>3#include <vector>4#include <queue>5#include <fstream>6#include <stdexcept>7 using namespacestd;8 9 structscoreTen { One intid_; A stringname_; - intscore_; - theScore (intIdConst string&name,intscore) - : id_ (ID), name_ (name), Score_ (score) - { } - }; + - classComp + { A Public: at BOOL operator() (ConstScore &s1,ConstScore &S2) - { - if(S1.score_! =s2.score_) - returnS1.score_ <s2.score_; - if(S1.name_! =s2.name_) - returnS1.name_ >s2.name_; in returnS1.id_ >s2.id_; - } to }; + -typedef priority_queue<score, Vector<score>, comp>scorelist; the * voidReadFile (Const string&filename, Scorelist &scores); $ voidPrintscorelist (Scorelist &scores);Panax Notoginseng - intMainintargcChar Const*argv[]) the { + Scorelist scores; A theReadFile ("Score.txt", scores); + printscorelist (scores); - } $ $ voidReadFile (Const string&filename, Scorelist &scores) - { -Ifstreaminch(Filename.c_str ()); the if(!inch) - ThrowRuntime_error ("File open failed");Wuyi the stringLine ; - while(Getline (inch, line)) Wu { - intID; About Charname[ -] = {0}; $ intscore; -SSCANF (Line.c_str (),"%d%s%d", &id, Name, &score); - Scores.push (Score (ID, name, score)); - } A + inch. Close (); the } - $ voidPrintscorelist (Scorelist &scores) the { the while(!scores.empty ()) the { theScore S =scores.top (); - Scores.pop (); incout <<"id ="<< s.id_ <<"name ="<< s.name_ <<"score ="<< s.score_ <<Endl; the } the}
The above example is a very simple sort of transcript. Simply write a collation class and reload the () function call symbol on the sorting class.
This code is used to forget when to review
C + + Learning Path: Priority queuing using templates (to prevent forgetting)