The priority_queue class can be used to store elements of a certain type (int, s
ID: 3863783 • Letter: T
Question
The priority_queue class can be used to store elements of a certain type (int, string, etc.) and then retrieve them in decreasing order. You can declare a priority_queue of integers like this: priority_queue pq; You can perform the following operations on a priority_queue of integers: void push (int value);//inserts a new integer in to the priority queue int top ();//returns the current biggest int in the queue void pop ();//removes the current biggest int from the queue int size ();//returns the number of ints in the queue Using this knowledge, write a C++ program to do the following: Read a list of numbers from a file, called file.txt, which has one number per line. You should use an if stream and either the extraction operator (> >) or the get line method. Put these numbers into a priority. queue. Print the numbers to the screen in descending order. You should divide your program into these functions: void read Numbers (cost string& filename, priority_queue & pq) This function takes a filename by cost reference and a priority queue by reference. It should open filename using an if stream and read the numbers into pq. void print Numbers (priority_queue & pq) This function should repeatedly print and then remove the biggest thing in pq.Explanation / Answer
Please refer below code
#include<cstdlib>
#include<iostream>
#include<fstream>
#include<queue>
using namespace std;
void readNumbers(const string& filename, priority_queue<int>& pq)
{
std::ifstream myfile(filename.c_str()); //input file name
int a;
while(myfile >> a) //reading file element by element
pq.push(a); //enqueue into priority queue
}
void printNumbers(priority_queue<int>& pq)
{
while(pq.size() > 0)
{
cout<<pq.top()<<" "; //printing top element of PQ
pq.pop(); //removing top element of PQ
}
}
int main()
{
string filename;
std::priority_queue<int> pq;
cout<<"Enter Filename : ";
cin>>filename;
readNumbers(filename,pq);
printNumbers(pq);
return 0;
}
1.txt
83
149
94
541
575
926
972
681
905
924
393
243
Please refer below output for reference
Enter Filename : 1.txt
972 926 924 905 681 575 541 393 243 149 94 83
Process returned 0 (0x0) execution time : 2.880 s
Press any key to continue.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.