1 Replies - 1521 Views - Last Post: 11 November 2010 - 01:11 PM Rate Topic: -----

#1 krishan22  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 10-November 10

How can i use comparison operator in my own Priority Queue Class

Posted 11 November 2010 - 12:11 PM

Hi I am in beginner level in C++. I am making my own priority queue class, I have instruction that I want to use the comparison operator(operator <) for determine best priority. So how can I use that in my priority class???.Here just I tried:
template<typename T>
class MyPQ
{
public:
	vector<T> vecImp;
	MyPQ()
	{
	    vecImp.empty();
	}
	MyPQ(T &data)
	{
		push(data);
	}

	bool empty() const
	{
		if(vecImp.empty())
		{
			return true;
		}else
		{
			return false;
		}
	}

	void push(const T &data)
	{
		insertData(data);
		vecImp.push_back(data);
	}


	T pop()
	{
	// pop code

	}
	
	T getData()
	{
		return data;
	}
	
	void insertData(const T& insert)
	{
		data=insert;
	}

	bool operator< (const MyPQ& Q1)
	{
		return data < Q1.data;
	}

	~MyPQ()
	{

	}

private:
	T data;
};



So my problem where I can use the comparison method? in pop() method? or in the main routine?

Is This A Good Question/Topic? 0
  • +

Replies To: How can i use comparison operator in my own Priority Queue Class

#2 Martyr2  Icon User is online

  • Programming Theoretician
  • member icon

Reputation: 4421
  • View blog
  • Posts: 12,289
  • Joined: 18-April 07

Re: How can i use comparison operator in my own Priority Queue Class

Posted 11 November 2010 - 01:11 PM

Well you would use it in your pop function. Pop is going to need to iterate through the vector and find (from the way you constructed that < operator) which item has the greatest data value and pull that out of the list and return it. So you will be calling your operator from within pop. I am not quite sure what the purpose of the member variable "data" is serving here since really this class should be wrapped around your vector and everything will be dealing with values in vector itself, no need to keep track of values in "data".

But of course I don't have the entire picture here. The class itself though, to serve as a priority queue, doesn't need "data" and the class pop would use the < operator to see which value is greatest in the vector to return.

Hope that answered the question for you. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1