Jump to content
  • Advertisement
Sign in to follow this  
thedustbustr

priority que of pointers - dereference before sort?

This topic is 5397 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to create a std::priority_queue<System*> which sorts by the less than operator of the dereferenced system object, not by the object's memory address.
class System{
public:
int priority;
bool operator < (System& system) {
    if (priority < system.priority) return true; 
    return false; 
} void setPriority(int p) {priority=p;}
};
How can I do this? Thanks, Dustin

Share this post


Link to post
Share on other sites
Advertisement

template <
class Type,
class Container=vector<Type>,
class Compare=less<typename Container::value_type>
>
class priority_queue

change the Compare type to a functor that does a dereference and a compare.

Share this post


Link to post
Share on other sites
std::priority_queue has a type parameter for a comparator functor/function this is what you need.


#include <queue>
#include <functional>

struct System {

int priority;

bool operator<(const System& system) const {
return (priority < system.priority) ? true : false;
}

};


struct System_equals : public std::binary_function< const System* const, const System* const, bool > {

bool operator()(const System* const a, const System* const b) const {
return (*a < *b);
}

};

int main() {

std::priority_queue< System*, std::vector<System*>, System_equals > g;

return 0;

}

Share this post


Link to post
Share on other sites
I recommend that you do not overload operator< just for use by the priority queue. The problem is that the overloaded operator will be used every time you use the < operator. What if you want to sort by a different criteria elsewhere? I also recommend that you don't specialize less<System*> for the same reason.

Write a member function to compare priorities instead and use that in the functor rather than the < operator.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!