【问题标题】:stl priority_queue of C++ with struct带有结构的 C++ 的 stl priority_queue
【发布时间】:2013-03-24 17:56:07
【问题描述】:

我们如何将 STL priority_queue 用于 struct ? 任何 illustration 的 push & popping ,其中 struct 有多种数据类型?
说:struct thing { int a; char b;} glass[10];。
现在我如何使用“int a”将这个结构放在priority_queue 上进行排序?

【问题讨论】:

    标签: c++ struct priority-queue


    【解决方案1】:

    这是对your original question, which you deleted 的略微修改的答案,原因不明。原件包含足够的信息让您弄清楚这一点,但这里是:提供一个小于比较,使用 int 进行比较。

    您需要做的就是提供一个函子,该函子可以实现与严格弱排序的小于比较,或者为您的类提供一个小于运算符来实现相同的操作。该结构满足要求:

    struct thing
    {
        int a;
        char b;
        bool operator<(const thing& rhs) const
        {
            return a < rhs.a;
        }
    };
    

    然后

    std::priority_queue<thing> q;
    thing stuff = {42, 'x'};
    q.push(stuff);
    q.push(thing{4242, 'y'}); // C++11 only
    q.emplace(424242, 'z'); // C++11 only    
    thing otherStuff = q.top();
    q.pop();
    

    【讨论】:

    • 谢谢 ^_^ & 最后一件事:我将如何将 (3,a) 直接推送到队列?我不知道如何将 (3,a) 放入 'thing stuff= ...' 。
    • 在c++11中,你可以说q.push(thing{42, 'x'})或q.emplace(42, 'x')。如果没有 C++11 支持,需要给thing 一个构造函数。
    • 参数是否必须是 const 引用?为什么我们不能简单地做 bool operator
    【解决方案2】:

    为thing 重载&lt; 运算符:

    struct thing
    {
        int a;
        char b;
    
        bool operator<(const thing &o) const
        {
            return a < o.a;
        }
    };
    
    priority_queue<thing> pq;
    
    thing t1, t2, t3;
    
    // ...
    
    pq.push(t1);
    pq.push(t2);
    
    // ...
    
    t3 = pq.top();
    pq.pop();
    

    【讨论】:

      【解决方案3】:

      您需要实现一个比较函数或重载运算符来告诉优先级队列您希望按什么顺序对自定义数据进行排序。当优先级队列对您的数据进行排序时,它将需要一种方法来知道如何在它们之间进行比较。您必须通过将函数传递给自定义数据类或结构中的优先级队列或重载运算符来指定这一点。

      您可以查看this的答案。 This 可能会对您有所帮助。我试图解释将优先级队列用于自定义数据类型的多种方式。

      【讨论】:

        【解决方案4】:

        你可以这样做!

        struct example{
           int height;
           int weight;
        };
        
        struct comp{
                bool operator()(struct example a, struct example b){
                 //Sorting on the basis of height(Just for example)
                    return (a.height > b.height);
                }
            };
        
        // And here comes your priority queue
         priority_queue<struct example, vector<struct example>, comp> pq;
        struct example your_obj;
        pq.push(your_obj);
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-08-03
          • 2021-09-26
          • 1970-01-01
          • 1970-01-01
          • 2011-02-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多