Search code examples
c++c++11visual-studio-2013visual-c++-2010

creation of priority queue - c++


I want to create a general priority queue. yes I know this can be achieved with STL but I still don't have full understand of it and this is why I want to build one myself. When I say general I mean it in a sense it will act the same for int,string,any class,etc. I understand that each item in Queue needs to have at least 2 fields : 1. value 2. priority so I figure that only my value field should be a template but I found out there ain't such an option. I am a bit lost here about where I should locate the template and how to use it afterward.

edit1: The 1st 2 comments said my question is too broad so I'll try to narrow it down. lets say I got this start of my PQ:

template <class T>
class Stack
{
public: 
int priority
template <t> value
Stack(s); //Ctor
}

this code is how I fought it Should be written but it doesn't compile. also If I had methods in the class would I need to write before each implementation of each method :

 template<class T>

or maybe I can just use :

Stack<T>::Stack(int s) //Ctor

Solution

  • If you look at std::priority_queue<T, C, P> you'll see that it takes three template parameters:

    1. The value type T.
    2. The type of the underlying container C (defaulted to std:vector<T>).
    3. A binary predicate P defining the priority order on the elements of type T (defaulted to std::less<...>).

    That is, you'd just store whatever you need to store and define the priority using the binary predicate. If you want to store int objects with a separate priority you could, e.g., store a std::pair<int, priority_type> and provide a binary predicate comparing the second element of these pairs.

    I do realize that you want to implement the priority queue yourself but I would entirely follow the standard library model (well, I would move the predicate forward and possibly omit the customization of the underlying container).