Case 4-4 Windows message queue (25 points) (priority setting of priority queue)

The message queue is the foundation of the Windows system. For each process, the system maintains a message queue. If a specific event occurs during the process, such as mouse click, text change, etc., the system will add this message to the queue. At the same time, if the queue is not empty, the process cyclically obtains messages from the queue according to priority. Please note that a low priority value means a high priority. Please edit the program to simulate the message queue, add messages to the queue and get messages from the queue.

Input format: The
input first gives a positive integer N (≤10​5​​), and then N lines, each line gives an instruction- GET or PUT , which means to take out the message from the queue or add the message to the queue, respectively. If the command is PUT, there is a message name and a positive integer that indicates the priority of the message. The smaller the number, the higher the priority. The message name is a string of no more than 10 characters and no spaces; the title guarantees that the priority of the message in the queue is not repeated, and the input has at least one GET .

Output format:
For each GET instruction, output the name and parameters of the message with the highest priority in the message queue in one line. If there is no message in the message queue, the output EMPTY QUEUE! . There is no output for the PUT instruction.

Question idea:
1. This question uses the Priority_Queue container in the STL container. The header file is "queue". When using the priority queue, you need to reset the priority of the elements in the priority queue.
2. Priority settings are divided into basic data types (the larger the default data, the higher the priority) and structure data types (the "<" must be overloaded, and the compiler must report an error for the ">" overload).
3. Define a friend function friend operator <(Node a, Node b){return a.num> b.num} in the structure of this question Remember, it is the opposite of sort sorting bool CMP() defined by ourselves).

#include<iostream>
#include<queue>
#include<string>

using namespace std;
struct Node {
    
    
	string message;
	int num;
	friend bool operator<(Node a, Node b) {
    
     return a.num > b.num; }
};

int main()
{
    
    
	priority_queue<Node> que;
	Node t;
	string st;
	int n;
	cin >> n;
	ios::sync_with_stdio;	//这道题对时间的限制比较刁钻,第三个测试点有时过不去,问题不大,加上这句会好些。
	for (int i = 0; i < n; i++)
	{
    
    
		cin >> st;
		if (st[0] == 'P')
		{
    
    
			cin >> t.message >> t.num;
			que.push(t);
		}
		else
		{
    
    
			if (que.empty())
				cout << "EMPTY QUEUE!\n";
			else
			{
    
    
				cout << que.top().message << endl;
				que.pop();
			}
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/xdg15294969271/article/details/113948185