如何实现带有指针的c ++ priority_queue的排序方法 [英] How to implement sorting method for a c++ priority_queue with pointers
本文介绍了如何实现带有指针的c ++ priority_queue的排序方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的优先级队列声明为:
My priority queue declared as:
std::priority_queue<*MyClass> queue;
class MyClass {
bool operator<( const MyClass* m ) const;
}
未对队列中的项目进行排序。
is not sorting the items in the queue.
有什么问题?我不想实现一个不同的(比较)类。
What is wrong? I would not like to implement a different (Compare) class.
回答摘要:
问题是,指针地址是排序的。避免这种情况的唯一方法是比较指针的类。
The problem is, the pointer addresses are sorted. The only way to avoid this is a class that 'compares the pointers'.
现在实现为:
std::priority_queue<*MyClass, vector<*MyClass>, MyClass::CompStr > queue;
class MyClass {
struct CompStr {
bool operator()(MyClass* m1, MyClass* m2);
}
}
推荐答案
如果你希望ptr_less与std库的其余部分(binder,composers,...)兼容:
If you want the ptr_less to be compatible with the rest of the std library (binders, composers, ... ):
template<class T>
struct ptr_less
: public binary_function<T, T, bool> {
bool operator()(const T& left, const T& right) const{
return ((*left) <( *right));
}
};
std::priority_queue<MyClass*, vector<MyClass*>, ptr_less<MyClass*> > que;
否则您可以使用简化版本:
Otherwise you can get away with the simplified version:
struct ptr_less {
template<class T>
bool operator()(const T& left, const T& right) const {
return ((*left) <( *right));
}
};
std::priority_queue<MyClass*, vector<MyClass*>, ptr_less > que;
这篇关于如何实现带有指针的c ++ priority_queue的排序方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文