Question

Skills needed to complete this assignment: template metaprogramming. PROGRAMMING LANGUAGE: C++ PROMPT: Write a template version...

Skills needed to complete this assignment: template metaprogramming.

PROGRAMMING LANGUAGE: C++

PROMPT:

Write a template version of a class PQueue that implements a priority queue. A priority queue is a list of items that is always ordered by priority. Each item that is added to the list requires an associated priority value, an integer for this problem, where 0 represents the highest priority and larger values are lower in priority. Removing an item from the queue removes the item with the highest priority (the smallest priority value).

The class must have the following public functions

1. add: take a generic type as the item to be added and an integer as the priority and adds the item to the priority queue.

2. remove: removes and returns from the priority queue the item that has the highest priority. If multiple items have the same priority, anyone of them could be returned.

3. empty: returns true if the priority queue is empty, and false otherwise.

Defining other functions is optional

You can use any standard library classes except the priority_queue.

You must submit at least one file: pqueue.h. You can submit other files if they are necessary to compile your class.

Hints:

1. You can start with a basic type like char, then convert to class to a class template.

2. For class templates, you need to have the class definition and its member functions definitions in the same file, or to have all the files (header and implementation) including in the main program. Otherwise the compiler cannot link the files.

INPUT/OUTPUT EXAMPLE

Character queue:

Enter how many items you want to add to the queue: 4

Enter item and its priority: A 12

Enter item and its priority: B 1

Enter item and its priority: C 3

Enter item and its priority: D 0

Items in queue in order of priority:

D

B

C

A

String queue:

Enter how many items you want to add to the queue: 3

Enter item and its priority: alpha 3

Enter item and its priority: bravo 1

Enter item and its priority: charlie 2

Items in queue in order of priority:

bravo

charlie

alpha

MAIN.CPP

#include

#include

#include "pqueue.h"

#include "pqueue.cpp"

using namespace std;

template

void testPQueue(PQueue &pq)

{

int n;

cout << "Enter how many items you want to add to the queue: ";

cin >> n;

for(int i=0; i

{

T input;

int priority;

cout << "Enter item and its priority: ";

cin >> input >> priority;

p1.add(input, priority);

}

cout << "Items in queue in order of priority:" << endl;

while(!pq.empty())

{

cout << pq.remove() << endl;

}

}

int main()

{

PQueue pqc;

cout << "Character queue:" << endl;

testPQueue(pqc);

PQueue pqs;

cout << "String queue:" << endl;

testPQueue(pqs);

return 0;

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// pqueue.h

#ifndef PQUEUE_H_
#define PQUEUE_H_

#include <iostream>
#include <vector>
using namespace std;

// structure to represent the elements of the PQueue
template <class T>
struct Item
{
   T value;
   int priority;
};

template <class T>
class PQueue
{
   vector< Item<T> > queue; // queue to store the elements

public:
   void add(T value,int priority);
   T remove();
   bool empty();
};

// function to add the Item with value and priority at the end of queue
template <class T>
void PQueue<T>::add(T value, int priority)
{
   Item<T> item;
   item.value = value;
   item.priority = priority;
   queue.push_back(item);
}

// function to remove and return the value with highest priority i.e lowest priority value
template <class T>
T PQueue<T>::remove()
{
   if(!empty()) // if queue is not empty
   {
       int maxIdx = 0;
       // loop to find the index of the highest priority item
       for(size_t i=1;i<queue.size();i++)
       {
           if(queue[i].priority < queue[maxIdx].priority)
           {
               maxIdx = i;
           }
       }

       T value = queue[maxIdx].value; // get the value of the highest priority item
       queue.erase(queue.begin()+maxIdx); // remove the item

       return value; // return the value
   }

   return T(0);
}

// function to return if the queue is empty or not
template <class T>
bool PQueue<T>::empty()
{
   return queue.size() == 0;
}

#endif

//end of pqueue.h

//main.cpp : C++ program to test PQueue class

#include <iostream>
#include "pqueue.h"
using namespace std;

template <class T>

void testPQueue(PQueue<T> &pq)
{

   int n;

   cout << "Enter how many items you want to add to the queue: ";

   cin >> n;

   for(int i=0; i<n;i++)
   {

       T input;

       int priority;

       cout << "Enter item and its priority: ";

       cin >> input >> priority;

       pq.add(input, priority);

   }

   cout << "Items in queue in order of priority:" << endl;

   while(!pq.empty())
   {
       cout << pq.remove() << endl;
   }

}

int main() {

   PQueue<char> pqc;
   cout << "Character queue:" << endl;
   testPQueue(pqc);
   PQueue<string> pqs;
   cout << "String queue:" << endl;
   testPQueue(pqs);
   return 0;
}

//end of main.cpp

Output:

Add a comment
Know the answer?
Add Answer to:
Skills needed to complete this assignment: template metaprogramming. PROGRAMMING LANGUAGE: C++ PROMPT: Write a template version...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 1. (40’) In myStack.cpp, implement the member functions of the class myStack, which is the class...

    1. (40’) In myStack.cpp, implement the member functions of the class myStack, which is the class for integer stacks. 2. (20’) In stackTest.cpp, complete the implementation of function postfixTest(), which use an integer stack to evaluate post-fix expressions. For simplicity, you can assume the post-fix expression is input character by character (i.e., not an entire string), and each operand is a non-negative, single-digit integer (i.e., 0,1,…,9). However, you are supposed to detect invalid/ illegal post-fix expression input, e.g., “4 5...

  • Hello, I have some errors in my C++ code when I try to debug it. I...

    Hello, I have some errors in my C++ code when I try to debug it. I tried to follow the requirements stated below: Code: // Linked.h #ifndef INTLINKEDQUEUE #define INTLINKEDQUEUE #include <iostream> usingnamespace std; class IntLinkedQueue { private: struct Node { int data; Node *next; }; Node *front; // -> first item Node *rear; // -> last item Node *p; // traversal position Node *pp ; // previous position int size; // number of elements in the queue public: IntLinkedQueue();...

  • c++ programming : everything is done, except when you enter ("a" ) in "F" option ,...

    c++ programming : everything is done, except when you enter ("a" ) in "F" option , it does not work. here is the program. #include <iostream> #include <string> #include <bits/stdc++.h> #include <iomanip> #include <fstream> using namespace std; #define MAX 1000 class Inventory { private: long itemId; string itemName; int numberOfItems; double buyingPrice; double sellingPrice; double storageFees; public: void setItemId(long id) { itemId = id; } long getItemId() { return itemId; } void setItemName(string name) { itemName = name; } string...

  • in C++ creat a DynamicQueue class, add a new data member called count to trace the...

    in C++ creat a DynamicQueue class, add a new data member called count to trace the total number of node you have in current queue (you need to modify some member functions for adding count). Add a member function called displayQueue() to display values stored in each node in the current queue, also the total number of nodes in the queue. You also need to have a driver program (refer to Tester) to test your modified new class and new...

  • PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite...

    PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite the code implementing a template class using a linked list instead of an array. Note: The functionality should remain the same *************************************************************************************************************** /** * Stack implementation using array in C/procedural language. */ #include <iostream> #include <cstdio> #include <cstdlib> //#include <climits> // For INT_MIN #define SIZE 100 using namespace std; /// Create a stack with capacity of 100 elements int stack[SIZE]; /// Initially stack is...

  • I've posted 3 classes after the instruction that were given at start You will implement and...

    I've posted 3 classes after the instruction that were given at start You will implement and test a PriorityQueue class, where the items of the priority queue are stored on a linked list. The material from Ch1 ~ 8 of the textbook can help you tremendously. You can get a lot of good information about implementing this assignment from chapter 8. There are couple notes about this assignment. 1. Using structure Node with a pointer point to Node structure to...

  • USE C++. Just want to confirm is this right~? Write a class named RetailItem that holds...

    USE C++. Just want to confirm is this right~? Write a class named RetailItem that holds data about an item in a retail store. The class should have the following member variables: description: A string that holds a brief description of the item. unitsOnHand: An int that holds thw number of units currently in inventory. price: A double that holds that item's retail price. Write the following functions: -appropriate mutator functions -appropriate accessor functions - a default constructor that sets:...

  • lab 11 Do not change main.cpp, i need c++ code for queue.h and queue.cpp Given the...

    lab 11 Do not change main.cpp, i need c++ code for queue.h and queue.cpp Given the complete main() function, partial queue class header queue.h, and queue.cpp, you will complete the class declaration and class implementation. The following member functions are required: constructor enqueue() dequeue() You may elect to create the following helper functions: isFull() isEmpty() A description of these ADT operations are available in this Zybook and in the textbook's chapter 17. Example: If the input is: 3 Led Zepplin...

  • I need help with this assignment, can someone HELP ? This is the assignment: Online shopping...

    I need help with this assignment, can someone HELP ? This is the assignment: Online shopping cart (continued) (C++) This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program). (1) Extend the ItemToPurchase class per the following specifications: Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt) Public member functions SetDescription() mutator & GetDescription() accessor (2 pts) PrintItemCost() - Outputs the item name followed by...

  • Write a Pseudocode for the below implementation of Greedy Algorithm to find the number of the...

    Write a Pseudocode for the below implementation of Greedy Algorithm to find the number of the least truck can be used to deliver items in C++. #include <iostream> using namespace std; void TruckFunction(int n , int w[], int limit) { int trucks = 1; int weight = 0; cout<<endl<<"Items carried in truck " <<trucks<<": "<<endl; for ( int i = 0 ; i < n ; i ++ ) { if((weight + w[i]) <= limit) { weight += w[i]; cout<<"Item...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT