簡體   English   中英

priority_queue <>比較指針?

[英]priority_queue<> comparison for pointers?

因此,我將STL priority_queue <>與指針一起使用...我不想使用值類型,因為創建一堆僅用於優先級隊列的新對象將非常浪費。 所以...我正在嘗試這樣做:

class Int {
public:
    Int(int val) : m_val(val) {}
    int getVal() { return m_val; }
private:
    int m_val;
}


priority_queue<Int*> myQ;

myQ.push(new Int(5));
myQ.push(new Int(6));
myQ.push(new Int(3));

現在,我如何編寫比較函數以使它們在Q中正確排序? 或者,有人可以建議替代策略嗎? 我真的需要priority_queue接口,並且不想使用復制構造函數(因為有大量數據)。 謝謝

編輯: int只是一個占位符/示例...我知道我可以在C / C ++中使用int大聲笑...

您可以明確指定隊列應使用的比較器。

#include <iostream>
#include <sstream>
#include <functional>
#include <vector>
#include <queue>

class Int {
public:
    Int(int val) : m_val(val) {}
    int getVal() { return m_val; }
    bool operator<(const Int &other) const { return m_val < other.m_val; }
private:
    int m_val;
};

template<typename Type, typename Compare = std::less<Type> >
struct pless : public std::binary_function<Type *, Type *, bool> {
    bool operator()(const Type *x, const Type *y) const
        { return Compare()(*x, *y); }
};

int main(int argc, char *argv[]) {
    std::priority_queue<Int*, std::vector<Int*>, pless<Int> > myQ;

    for (int i = 1; i < argc; i++) {
        std::stringstream ss(argv[i]);
        int x;
        ss >> x;
        myQ.push(new Int(x));
    }

    for (; !myQ.empty(); delete myQ.top(), myQ.pop())
        std::cout << myQ.top()->getVal() << std::endl;

    return 0;
}

一種肯定會起作用的選項是用shared_ptr<Int>替換Int* ,然后為shared_ptr<Int>實施operator<

bool operator<(const shared_ptr<Int> a, const shared_ptr<Int> b)
{
    return a->getVal() < b->getVal();
}

整數的大小與32位系統上的指針相同。 在64位系統上,指針將是原來的兩倍。 因此,使用正整數更簡單/更快/更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM