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.
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: