The heap does indeed store its own instance of node_compare
but does not default construct it but copy constructs it from the object you pass in the constructor.
So in the line priority_queue pq(cmp);
the queue copies the cmp
object using the automatically generated copy constructor of the node_compare
class.
If you call cmp.set(3, 10);
before creating the priority_queue
it should be set in the comparator of the queue, too.
I'm afraid you can't change the comparator once you created the heap. The heap object has a value_comp()
member function which returns a const
reference to the comparator, so you can't change the returned comparator. I think you can not change the comparator since that would invalidate the data structure in the heap.
But you can store a reference to the distance vector inside the comparator:
struct node_compare {
const std::vector<int> &dist_;
node_compare(const std::vector<int> &dist) : dist(dist) {};
bool operator()(const int& n1, const int& n2) const {
return dist_[n1] > dist_[n2];
}
};
You only have to be carefull that you don't change the passed distance vector after you added elements to your heap.