簡體   English   中英

在 C++ 中,當添加到調用 bubbleUp 函數的 minHeap 時,如何按字典順序比較具有相同優先級的兩個事物?

[英]In C++, when adding onto a minHeap, which calls the bubbleUp function, how can I lexicographically compare two things that have the same priority?

在 C++ 中,當添加到調用 bubbleUp 函數的 minHeap 時,如何按字典順序比較具有相同優先級的兩個事物?

我希望按字典順序比較時較小的值首先出現在堆中。 if條件應該是什么?

如果代碼是這樣的:

void MinHeap::bubbleUp(int pos)
{
    if (pos >= 0 && vec[pos].second < vec[(pos-1)/d].second)]  
    {
        swap(vec[pos], vec[(pos-1)/d)];
        bubbleUp(vec[(pos-1)/d)];
    }
    else if (pos >= 0 && vec[pos].second == vec[(pos-1)/d].second)
    {
        if(vec[pos].first < vec[(pos-1)/d].first)
        {
            swap(vec[pos], vec[(pos-1)/d];
            bubbleup((pos-1)/d];
        }
    }
}

作為一些參考,向量包含一對字符串和優先級。

如果您想要數據的特定排序順序,您可以使用內置比較函數來實現“某物大於某物”,或者,您可以提供自定義排序函子。

為了使用 Functor,您需要使用所有 3 個模板參數實例化std::priority_queue (MinHeap)。 最后一個將是比較函子。

作為底層容器,您可以使用std::vector

示例程序可能如下所示:

#include <iostream>
#include <vector>
#include <queue>

struct MyData {
    int a{};
    int b{};
    friend std::ostream& operator << (std::ostream& os, const MyData& m) {
        return os << "a: " << m.a << "   b: " << m.b << '\n';
    }
};

struct Compare {
    bool operator()(const MyData& md1, const MyData& md2) {
        if (md1.a == md2.a)
            return md1.b > md2.b;
        else
            return md1.a > md2.a;
    }
};
using UnderlyingContainer = std::vector<MyData>;

using MinHeap = std::priority_queue<MyData, UnderlyingContainer, Compare>;

int main() {
    MyData md1{ 5,5 }, md2{ 5,4 }, md3{ 5,3 }, md4{ 5,2 }, md5{ 5,1 };

    MinHeap mh{};

    mh.push(md1); mh.push(md4); mh.push(md3); mh.push(md2); mh.push(md5);

    for (size_t i = 0; i < 5; ++i) {
        std::cout << mh.top();
        mh.pop();
    }
    return 0;
}

暫無
暫無

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

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