Using this knowledge, write a C++ program to do the following: Read a list of nu
ID: 3863778 • Letter: U
Question
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. Please write your program on the next page.Explanation / Answer
#include <iostream>
#include<fstream>
#include <queue>
#include <vector>
using namespace std;
template<typename T> void printNumbers(T& pq) {
while(!pq.empty()) {
std::cout << pq.top() << " ";
pq.pop();
}
std::cout << ' ';
}
template<typename T> void readNumbers(const string filename,T& pq){
ifstream infile;
infile.open(filename);
int num;
while (!infile.eof()){
infile >> num;
pq.push(num);
}
infile.close();
}
int main()
{
std::priority_queue<int, std::vector<int>, std::greater<int> > pq;
readNumbers("input.txt",pq);
printNumbers(pq);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.