简体   繁体   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?

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 时,如何按字典顺序比较具有相同优先级的两个事物?

I want the value that is smaller when compared lexicographically to come first in the heap.我希望按字典顺序比较时较小的值首先出现在堆中。 What should be the if condition be? if条件应该是什么?

If the code is something like this:如果代码是这样的:

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];
        }
    }
}

For some reference, the vector contains pair of string and priority.作为一些参考,向量包含一对字符串和优先级。

If you want a specific sorting order for your data, you can either use a build in comparison function for "something is greater than something else", or, you can provide a custom sort Functor.如果您想要数据的特定排序顺序,您可以使用内置比较函数来实现“某物大于某物”,或者,您可以提供自定义排序函子。

In order to use the Functor, you need to instantiate the std::priority_queue (the MinHeap) withall 3 template parameters.为了使用 Functor,您需要使用所有 3 个模板参数实例化std::priority_queue (MinHeap)。 The last one will be the compare functor.最后一个将是比较函子。

As underlying container you can take a std::vector .作为底层容器,您可以使用std::vector

An example program could look like the following:示例程序可能如下所示:

#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