0

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

I want the value that is smaller when compared lexicographically to come first in the heap. What should be the if condition be?

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.

  • 3
    How do your objects look like? If they are just `std::string`s, then ordinary `operator<` already does a lexicographic comparison. Otherwise it's not possible to tell you *how* to compare if we don't even know *what* to compare... – Aconcagua Oct 14 '21 at 07:48
  • You'll get more useful replies when you provide your (relevant) code, sample data, expected output, and what you get instead. – trincot Oct 14 '21 at 08:04

1 Answers1

0

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. The last one will be the compare functor.

As underlying container you can take a 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;
}
A M
  • 14,694
  • 5
  • 19
  • 44