使用std::shared_ptr的std::priority_queue派生类编译错误

compilation error with std::priority_queue derived class using std::shared_ptr

本文关键字:std 派生 错误 queue 编译 shared ptr 使用 priority      更新时间:2023-10-16

我从std::priority_queue派生来实现一些专门的方法。其中之一当我添加一个元素并且队列已满时,最小的元素将从队列中删除。

template<typename T,
     typename Sequence = std::vector<T>,
     typename Compare = std::less<typename Sequence::value_type> >
class fixed_priority_queue : public std::priority_queue<T, Sequence, Compare> {
    friend class BCQueue_; // to access maxSize_
public:
fixed_priority_queue(unsigned int maxSize) 
: maxSize_(maxSize) {}
void insertWithOverflow(const T& x) {
    if (this->size() == maxSize_) {
        auto beg = this->c.begin();
        auto end = this->c.end();
        auto min = std::min_element(beg, end);
        if(x > *min) {
            *min = x;
            std::make_heap(beg, end);
        }
    }
    else {
       this->push(x);
    }
}
// ...
private:
    fixed_priority_queue() {} 
    const unsigned int maxSize_;
};

这是我使用的比较器:

class ScoreLessThan : public std::binary_function<
    std::shared_ptr<CCandidate>, std::shared_ptr<CCandidate>, bool> {
public:
    bool operator()(
        const std::shared_ptr<CCandidate>& a, const std::shared_ptr<CCandidate>& b) const {
        return a->score > b->score;
    }
};

我包装了派生的fixed_priority_queue类,以保持功能稍微分开,所以最后我有了这个:

class BCQueue_ : public fixed_priority_queue<
    std::shared_ptr<CCandidate>, std::vector<std::shared_ptr<CCandidate> >,      ScoreLessThan> {
public:
    BCQueue_(size_t maxSize)
    : fixed_priority_queue(maxSize) {}
    bool willInsert(float score) {
        return size() < maxSize_ || top()->score < score;
    }
};

我可以这样使用:

BCQueue_ queue(30);

CCandidate只是一些数据的保存器。其中一个属性是score字段,我在上面的比较器中使用它。

当我使用上面的类与CCandidate作为原始指针所有编译有问题和工作良好,现在我想用std::shared_ptr替换原始指针(如我上面所做的),我得到一个编译错误:


    ... 199:5: error: no match for ‘operator>’ in ‘x >min.__gnu_cxx::__normal_iterator::operator* [with _Iterator =  std::shared_ptr*, _Container = std::vector >, __gnu_cxx::__normal_iterator::reference = std::shared_ptr&]()’
...
... :199:5: note: candidates are:
... :199:5: note: operator>(int, int) 
... :199:5: note:   no known conversion for argument 2 from ‘std::shared_ptr’ to ‘int’

也许这是一个简单的问题。如果我正确地定义了比较器,或者如果我需要改变insertWithOverflow() x > *min中的比较,我不知道我应该在那里改变什么。

我应该提到的是,我已经在stackoverflow上找到了' insertWithOverflow'的实现,这正好适合我需要的。查看这里:如何使STL's priority_queue固定大小

如前所述,使用原始指针所有这些都不是问题。有人能帮我一下吗?提前感谢!

您需要在函数中的任何地方使用指定的比较函数:

using std::priority_queue<T, Sequence, Compare>::comp;
void insertWithOverflow(const T& x) {
    if (this->size() == maxSize_) {
        auto beg = this->c.begin();
        auto end = this->c.end();
        auto min = std::min_element(beg, end, comp);
        if(comp(*min, x)) {
            *min = x;
            std::make_heap(beg, end, comp);
        }
    }
    else {
       this->push(x);
    }
}