The only way to find an element in a priority queue in less-than-linear time without sacrificing the asymptotic performance of priority queue operations is to keep track of the position of each element upon each priority queue operation.
The only library I found that provides the necessary functionality is libpqueue
, now available here: https://github.com/vy/libpqueue.
It works by using user-defined callback functions cmppri()
, getpri()
, setpri()
, getpos()
, setpos()
, which are called by the library each time the queue is updated.
The intended usage pattern is to define a wrapper data structure like:
typedef struct {
pqueue_pri_t pri;
void *data;
size_t pos;
} node_t;
and accessor functions like:
static size_t get_pos(void *a) {
return ((node_t *) a)->pos;
}
static void set_pos(void *a, size_t pos) {
((node_t *) a)->pos = pos;
}
This allows one to find the position of a node in O(1)
time, at the expense of the overhead for creating the wrapper structure and the callback calls. If you need to find an element by name (and not by node_t pointer), you can easily use a std::unordered_map
or similar as a backend.
libpqueue
is standalone plain C under Apache license.