starting with priority_queues, I have a problem like this: I need elements to be stored in a queue, but the criterion how they are sorted is not included in the elements itself, but somewhere different, like in a map:
std::map<element, value> element_values;
std::priority_queue<element> queue;
What I need now is something like that:
struct Comp
{
std::map<...>& the_map;
Cpmp(std::map<...> _map) : the_map(_map) {}
bool operator() (element a, element b)
{
return the_map[a] < the_map[b];
}
}
Comp comp(element_values);
std::priority_queue<element, std::vector<element>, comp> queue; // does not work
std::priority_queue<element, std::vector<element>, Comp> queue; // does work but I'd not be able to pass values to the constructor
The elements itself have no intrensic order. A workaround would be to define a struct wrapping this stuff up, but maybe someone knows a smarter way. I also thought about providing a compare function only valid in my current scope (which itself is a function), but as far as I know C++ does not support that, at least not with capturing local variables like I would need.
The
std::priority_queue<T, Cont, Comp>take the comparison object type as template argument. To pass an object referencing something, you need to pass it as constructor argument: