Question #37623

Create a c++ program with heaps. It should receive input until they insert "quit". When the user inputs "add" followed by a number it should store the number. When the user says "list" it should print the numbers inserted in a list from max to min. when the user enter "deletemax" the biggest number should be deleted from the stored numbers. The user should be able to continue inserting what they want to do until they want to quit.

Expert's answer

Answer on Question #37623 – Programming - C++


#include <iostream>
#include <string>
#include <queue>
#include <sstream>
using namespace std;
int parseNumber(string pStr)
{
    stringstream lStream(pStr);
    string temp;
    int rNumber;
    lStream >> temp >> rNumber;
    return rNumber;
}
void printQueue(priority_queue<int> pQueue)
{
    for(int i = pQueue.size(); i > 0; --i)
    {
        cout << pQueue.top() << " -";
        pQueue.pop();
    }
    cout << endl;
}
int main()
{
    priority_queue<int> lQueue;
    string lCommand;
    getline(cin, lCommand);
    while(lCommand != "quit")
    {
        if(lCommand[0] == 'a')
            lQueue.push(parseNumber(lCommand));
        else if(lCommand == "list")
        {
            printQueue(lQueue);
        }
        else if(lCommand == "deletemax")
        {
            lQueue.pop();
        }
        else
        {
            cout << "Wrong command" << endl;
        }
        getline(cin, lCommand);
    }
    return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS