Google Answers Logo
View Question
 
Q: Priority Queue C++ ( Answered 5 out of 5 stars,   1 Comment )
Question  
Subject: Priority Queue C++
Category: Computers > Programming
Asked by: zeus48-ga
List Price: $75.00
Posted: 07 Dec 2002 19:40 PST
Expires: 06 Jan 2003 19:40 PST
Question ID: 121136
I need to have a program problem answered i have been given the header
file and need to create a main and source file using an array of queues for this.

#ifndef PRIORITYQUEUE_H
#define PRIORITYQUERE_H

#include <stdlib.h>
#include <queue>
#include <iostream>
#include <assert.h>
using namespace std;

template <class Item>
class Priorityqueue
{
public:
	enum {HIGHEST = 10}
	Priorityqueue();
	void insert (const Item& entry, unsigned int priority);
	Item get_front();
	size_t size() const;
	bool is_empty() const;
private:
	queue<Item> queues [HIGHEST + 1];
};
#include "priorityqueue.tem"
#endif

needs to basicaly take in hard coded numbers ie pqueue.insert(3,1)
and so on and delete return front and the rest of the functions

needed by 12/12/02   -- payment = full working code

Request for Question Clarification by mathtalk-ga on 08 Dec 2002 05:46 PST
Hi, zeus48-ga:

Thanks for posting the interesting question.  I can quickly implement
the desired class in C++ for you, once the basic goal is clarified as
follows:

1) Correct/clarify any syntax in the given header file.  For example,
the first line refers to a macro PRIORITYQUEUE_H in a common way that
would require the same identifier in the second line, where it appears
to be misspelled.  What is the file "priorityqueue.tem" to be included
at the bottom of the header file, and what is its purpose?

2) The "source file" is supposed to implement a class template for:

template <class Item> class Priorityqueue

with an array of queues, indexed from 0 to 10, with entries of type
Item.  I assume that of the member functions shown, the insert member
function should be defined so that it acts on queues[priority] using
the second argument shown, and is otherwise "inherited" from the
insert member function on template class queue.  Please confirm this
and give a similarly brief description of the other member functions
behaviors, esp. that get_front() has a side effect of removing an item
of highest available priority from the priority queue.

3) The "main" program is to be a test harness type program which
demonstrates the creation of object Priorityqueue<int> pqueue, the
effect of insert and other member functions on the object, and finally
its deletion.  Where you say "front" in this connection, I assume you
mean get_front().

Finally what degree of attention should be given to errors and
exception handling, and what philosophy (if any) is desired about
this.  To give an example, what might be the desired behavior if
get_front() is applied to an empty priority queue?  Or if the second
argument of insert is greater than 10?

regards, mathtalk-ga

Clarification of Question by zeus48-ga on 08 Dec 2002 17:39 PST
1. second line should read #define PRIORITYQUEUE_H 
2. priorityqueue.tem is to include the actions of all of the previous
functions I beleive.
3."I assume that of the member functions shown, the insert member
function should be defined so that it acts on queues[priority] using
the second argument shown, and is otherwise "inherited" from the
insert member function on template class queue." -- Correct
4.get_front() is to --return and remove-- the highest priority 
5."The "main" program is to be a test harness type program which
demonstrates the creation of object Priorityqueue<int> pqueue, the
effect of insert and other member functions on the object, and finally
its deletion.  Where you say "front" in this connection, I assume you
mean get_front()." -- Correct (typo)
6. errors are to end program using assert i believe. any attention to
get_front if class = NULL should abort program with no responce and if
greater then 10 was inserted as the priority, it would be nice to have
the priority class extended to 11, but proboly eaisest if it was to
end the program. since the inserts are hard coded it shouldnt cause
too much of a problem

Output should look something like
// with something like this hard coded 
pqueue.insert (23,1);
pqueue.insert (36,2);
pqueue.size();
pqueue.insert (76,3);
pqueue.insert (11,4);
pqueue.get_front();
pqueue.insert (34,6);
pqueue.insert (67,5);
pqueue.size();

//OUT PUT
2
23 had high priority and was removed
5

//or 
23 was set to 1
36 was set to 2
size = 2
76 was set to 3
11 was set to 4
23 had highest priority and was removed
34 was set to 6
67 was set to 5
size = 5 //because 23 was removed
//and i beleive if get_front was called it should be 
36 had highest priority and was removed

Clarification of Question by zeus48-ga on 08 Dec 2002 18:16 PST
Thanks for attempting mathtalk-ga< a timely responce is nessary and
will be very, VERY rewarded. $$

Request for Question Clarification by mathtalk-ga on 09 Dec 2002 07:50 PST
Okay, zeus48-ga:

Thanks for the clarification.  Let me point out one other syntax
problem with the given header file, a missing semi-colon after the
enum {HIGHEST=10} line.

I think what you are saying about file "priorityqueue.tem" is that it
contains the templatized code to implement the given methods for the
priorityqueue class template, what might otherwise be called
"priorityqueue.cpp", especially if it were simply a C++ class rather
than a template.

I have created the necessary files and should get it all debugged
tonight, in plenty of time for your deadline.  Would you care to
explain the relationship, if any, between the assignment here and the
"standard" class template priority_queue usually implemented by the
STL (standard template library)?

regards, mathtalk-ga

Clarification of Question by zeus48-ga on 09 Dec 2002 14:08 PST
mathtalk-ga 

Im not sure what you are asking about ---
".  Would you care to explain the relationship, if any, between the
assignment here and the "standard" class template priority_queue
usually implemented by the
STL (standard template library)?"  
Im not following some of the descriptions you're using.
with a little more description i could maybe help better

Clarification of Question by zeus48-ga on 11 Dec 2002 08:46 PST
Everything going alright?

Request for Question Clarification by mathtalk-ga on 11 Dec 2002 11:38 PST
Hi, zeus:

Yes, I'm playing around with the constructor some.  Give me a couple
more hours and I think I'll be happy enough with the three files to
post it as an answer, subject to any follow up clarifications.  I'm
building the main() program as a simple console app in Visual
Studio.Net C++.  What platform will you use?

regards, mathtalk-ga

Clarification of Question by zeus48-ga on 11 Dec 2002 13:52 PST
Ill be running it it visual studio.net or the previous visual studio 6.0
Answer  
Subject: Re: Priority Queue C++
Answered By: mathtalk-ga on 11 Dec 2002 15:30 PST
Rated:5 out of 5 stars
 
Hi, zeus48-ga:

In implementing the template class Priorityqueue, I see one basic
point that we need to resolve, a difference (perhaps) in our
interpretation of the "ordering" of the queues' priorities.

The header file uses the word HIGHEST to denote 10, or the last of the
queue array entries.  While one might interpret this to mean only
"highest index", my suspicion was that as this index is labelled
"priority" in terms of the class's interface for insertions, the most
likely possibility is that the higher the index, the higher the
priority.

Therefore the output from my program, running the test cases you
designed, differs from the output that you anticipated precisely in
that the call to get_front returns 11 rather than 23.

It is a minor point; the change to the code to order the priorities
oppositely would be trivial.  We just need to agree on which direction
is correct (and, of course, whatever you think is by definition
correct, despite my "initiative").

Let's begin with the files, so you can copy them down for your own
testing.  I can then do some comments, clarifications, etc.

>>>>>>>>>>>> BEGIN priorityqueue.h >>>>>>>>>>>>>>>

#ifndef PRIORITYQUEUE_H 
#define PRIORITYQUEUE_H 
 
#include <stdlib.h> 
#include <queue> 
#include <iostream> 
#include <assert.h> 
using namespace std; 
 
template <class Item> 
class Priorityqueue 
{ 
public: 
 enum {HIGHEST = 10}; 
 Priorityqueue(); 
 void insert (const Item& entry, unsigned int priority); 
 Item get_front(); 
 size_t size() const; 
 bool is_empty() const; 
private: 
 queue<Item> queues [HIGHEST + 1]; 
}; 
#include "priorityqueue.inc" 
#endif 

<<<<<<<<<<<<< END OF priorityqueue.h <<<<<<<<<<<<<<<<

>>>>>>>>>>>>> BEGIN priorityqueue.inc >>>>>>>>>>>>>>>

// definitions of template methods go here

// first, the "empty" constructor
template<class Item> 
	Priorityqueue<Item>::Priorityqueue()
	: queues()
	{
	}

template<class Item> 
	void Priorityqueue<Item>::insert(
		const Item& entry, 
		unsigned int priority)
	{
		// assume priority is valid
		assert(priority <= HIGHEST); 
		
		/* insert copy of entry as last 
		   element at given priority */
		queues[priority].push(entry);
	}

template<class Item>
	Item Priorityqueue<Item>::get_front()
	{
		/* caller must ensure Priorityqueue
		   contains an Item, e.g. !empty ;
		   otherwise behavior is undefined */
		   
		Item entry;
		int i;
		
		for(i = HIGHEST; i >= 0; i--)
		{
			if( ! queues[i].empty() ) 
			{
				entry = queues[i].front();
				queues[i].pop();
				return entry;
			}
		}
		
		// assume some queue was nonempty
		assert( i >= 0 );
	}
	
template<class Item> 
	size_t Priorityqueue<Item>::size() const
	{
		// total size from each queue
		size_t n = 0;
		
		for(int i = 0; i <= HIGHEST; i++)
		{
			n += queues[i].size();
		}
		
		return n;
	}

template<class Item>
	bool Priorityqueue<Item>::is_empty() const
	{
		// check for a nonempty queue 
		bool b = true;
		
		for(int i = 0; i <= HIGHEST; i++)
		{
			if ( ! queues[i].empty() )
			{ 
				b = false;
				break;
			}
		}
		
		return b;
	}

<<<<<<<<<<<<<<< END OF priorityqueue.inc <<<<<<<<<<<

>>>>>>>>>>>>>>> BEGIN zeusQueue.cpp >>>>>>>>>>>>>>>>


// Exclude rarely-used stuff from Windows headers
#define WIN32_LEAN_AND_MEAN		
#include <stdio.h>
// #include <tchar.h>

#include "priorityqueue.h"

int main(int argc, char* argv[])
{
	Priorityqueue<int> pqueue;
	 
	// with something like this hard coded  
	pqueue.insert (23,1); 
	pqueue.insert (36,2); 
	cout << pqueue.size() << '\n'; 
	pqueue.insert (76,3); 
	pqueue.insert (11,4); 
	cout << pqueue.get_front() << '\n'; 
	pqueue.insert (34,6); 
	pqueue.insert (67,5); 
	cout << pqueue.size() << '\n'; 

	return 0;
}

<<<<<<<<<<<<<<< END OF zeusQueue.cpp <<<<<<<<<<<

Notes:

  (1) I changed the name of the included file priorityqueue.tem to
priorityqueue.inc, because this is more consistent with the Visual
Studio IDE.  The header file and this included/template file can both
be "added" as Header Files to the project you want to build there
(allowing VS to recognize what needs to be rebuilt if changes are made
in one place or the other).

  (2) The output statements I implemented are rudimentary and can
easily be modified to match the text you used in the "sample output",
but I thought it would be more expeditious to give you this working
version so we can iron out more substantive issues quickly.

  (3) The implementation is quite lean.  I used asserts in the couple
of ways we discussed earlier, but made no further efforts to trap
incorrect assumptions.  We could certainly add a test for
pqueue.empty() to the test program ahead of pqueue.get_front().  Also
note that the interface does not allow us to know _what_ priority an
entry was listed at prior to being "popped" from the top of the
priority queue.  It was not possible in the amount of time to do a
thorough job of considering the design from the standpoint of memory
management, as one would assuredly want to do for production quality
code.

  (4) I anticipate that you will have a lot of questions about the
program and how it works.  Despite the brevity of the code, there are
actually a number of trenchant points about how the code is written. 
But let's get the program compiled and working on your end and then
worry about that.  I made the main program "simple" in the way one
would write a UNIX console program, and the way the #include <tchar.h>
line is commented out hints at this.  Let me know if you have any
problems "recreating" the project from these text files; I can zip up
the entire VS directory and put it out on the 'Net if need be.

regards, mathtalk-ga

Request for Answer Clarification by zeus48-ga on 11 Dec 2002 16:19 PST
everything is looking good so far i found some clarification on the
priorityqueue.tem. There should only be 2 files ZeusQueue.cpp and
priorityqueue.h.  So i took out the #include "priorityqueue.inc" and
put all of the data from priorityqueue.inc in that location.  The
program still works but im getting one error ???

c:\documents and settings\zeus\desktop\301final\priorityqueue.h(64) :
warning C4715: 'Priorityqueue<int>::get_front' : not all control paths
return a value

HERE:


 for(i = HIGHEST; i >= 0; i--) 
  { 
   if( ! queues[i].empty() )  
   { 
    entry = queues[i].front(); 
    queues[i].pop(); 
    return entry; 
   } 
  } 
   
  // assume some queue was nonempty 
  assert( i >= 0 ); 
 } //<------------ line 64
  
template<class Item>  
 size_t Priorityqueue<Item>::size() const 


************8
other then that its all working fine im going to add a little text
output to clear thing up.   if you wnat to try combining the two files
and see if your getting the same error. and see if you could work it
out?

Thanks 
Zeus48

Request for Answer Clarification by zeus48-ga on 11 Dec 2002 16:55 PST
More Problems now all i did was add output text i think its an
external problem with my computer????

Compiling...
priorityqueue.cpp
c:\documents and settings\zeus\desktop\priorityqueue.h(64) : warning
C4715: 'Priorityqueue<int>::get_front' : not all control paths return
a value
Linking...
LIBCD.lib(wincrt0.obj) : error LNK2001: unresolved external symbol
_WinMain@16
Debug/PriorityQ.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.

FinalLab.exe - 2 error(s), 1 warning(s)

Request for Answer Clarification by zeus48-ga on 11 Dec 2002 17:31 PST
OK MEVER MIND SKIP THE LAST MESSAGE I POSTED..................
I was running it in the wrong format...
Everything is working fine except the little 

c:\documents and settings\zeus\desktop\301final\priorityqueue.h(64) :
warning C4715: 'Priorityqueue<int>::get_front' : not all control paths
return a value

error

Request for Answer Clarification by zeus48-ga on 11 Dec 2002 17:37 PST
NEVER MIND I GOT IT :-)

all cleared up too i appreciate the help time to rate (and keep promises)

Thanks Much
Zeus48

Clarification of Answer by mathtalk-ga on 11 Dec 2002 19:49 PST
Yes, I got too tricky with the coding on get_front.  The quick fix is
to add:

return entry;

to the bottom of the routine, just to make the compiler happy that
"if" we fall through to there, the routine has a return value.  Of
course we should never get there, but the assert should be stated
differently, i.e. assert(false), to reflect that.

Congratulations on getting the program to work on your platform, and
let me know if I can be of assistance.

Thanks for rating my answer (and for the handsome tip!).  After
working on it for so many hours, the feedback means a lot!

regards, mathtalk-ga
zeus48-ga rated this answer:5 out of 5 stars and gave an additional tip of: $10.00
Fast, Clean, Clear.  When they say post price on how much its worth to
you they are sooo right worth every penny plus tip... Thanks

Comments  
Subject: Re: Priority Queue C++
From: haversian-ga on 08 Dec 2002 01:29 PST
 
I assume you're taking an OS class - good luck on finals!

Regrettably, I am not proficient enough in C to answer your question,
but if you do not recieve a response, I could answer a question asking
for fairly detailed pseudocode, optionally with real Java sections. 
The algorithm is fairly simple - keep separate queues for each
priority level; insert adds an item to the end of the appropriate
queue; remove checks each queue from highest to lowest, returning the
first item it finds.

Best of luck; I'm sorry I can't answer this for you, but I've got too
many exams to study for myself to both brush up on C and answer your
question properly.

-Haversian

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy