我不是很熟悉,从模板中派生,看到以下内容:类:: priority_queue一点儿也不使用比较谓词/模板参数
class BCQueue_;
template<typename T,
typename Sequence = std::vector<T>,
typename Compare = std::less<typename Sequence::value_type> >
class FixedPriorityQueue : public std::priority_queue<T> {
friend class BCQueue_; // to access private member maxSize_
public:
FixedPriorityQueue(unsigned int maxSize)
: maxSize_(maxSize) {}
// smallest item will be dropped if queue id full
void insertWithOverflow(const T& x) {
// ...
this->push(x);
// ...
}
private:
FixedPriorityQueue() {}
const unsigned int maxSize_;
};
class ScoreLessThan : public std::binary_function<CCandidate *, CCandidate *, bool> {
public:
bool operator()(
const CCandidate * a, const CCandidate * b) const {
std::wcout << a->score << " < " << b->score << std::endl;
return a->score > b->score;
}
};
class BCQueue_ : public FixedPriorityQueue<
CCandidate *, std::vector<CCandidate *>, ScoreLessThan> {
public:
BCQueue_(size_t maxSize)
: FixedPriorityQueue(maxSize) {}
bool willInsert(float score) {
return size() < maxSize_ || top()->score < score;
}
};
BSQueue bc(20);
bs.insertWithOverflow(new CCandidate(...));
// ...
在FixedPriorityQueue我有一个方法叫insertWithOverflow
那通过删除最小的元素来插入元素(如果队列已满)。 为了让事情有点分离,我从FixedPriorityQueue派生。基本上所有的工作都很好,除了比较器ScoreLessThan
似乎永远不会被调用。当我弹出/弹出元素时,他们不按照我预期的那样排列(得分)。
因此,这可能是更多的语法/使用问题,请耐心等待,但我找不到任何答案来解决问题。我虽然通过定义模板参数,一切都会解决。我在这里错过了什么?
感谢您的帮助!
你为什么选择继承?通过这样做,您允许用户调用常规的插入方法和溢出(实际上增长容器),并且还可能遇到其他问题,因为'priority_queue'不是基类。更喜欢构图(或者至少是私人继承) – 2013-04-23 15:18:11
@DavidRodríguez-dribeas:我知道它不是很干净,也不稳定。实际上,这个类是在另一个类中使用的,只是被那个封闭类所使用。但是当我解决问题时,我会记住你的评论。感谢提示! – 2013-04-23 15:30:11