std::priority_queue から派生させて、いくつかの特殊なメソッドを実装しました。これらのメソッドの 1 つは、要素を追加してキューがいっぱいになると、ある種の固定キューであり、最小の要素がキューから削除されます。
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
単なるホルダーです。1 つのプロパティは、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
かどうかはわかりませんが、実際にはそこで何を変更すればよいかわかりません。
ここで、必要なものにぴったり合う「insertWithOverflow」の実装をstackoverflowで見つけたことに言及する必要があります。こちらをご覧ください: STL の priority_queue を固定サイズにする方法
前述のように、生のポインターを使用すると、これはすべて問題ありません。誰かがこれについて私を助けてくれませんか。前もって感謝します!