开发者

How do you initialize a map that has a priority_queue as a value with the comparison object of the priority_queue?

开发者 https://www.devze.com 2023-02-11 10:08 出处:网络
What I would like to do is have a map that maps integer keys to priority_queues of pointers to a struct I have defined sorted by a comparison function I have also defined.

What I would like to do is have a map that maps integer keys to priority_queues of pointers to a struct I have defined sorted by a comparison function I have also defined.

That is, the type would be something like this,

map<int, priority_queue<object_t*, compare> > my_map;

where you may assume object_t is the my defined struct, and compare is a comparison function returning a boolean value.

Is there a way I can declare my_map to have the priority_queues already initialized with the comparison function? For example, can I declare it so that开发者_C百科 I can do the following,

my_map[1].push(object_ptr);
my_map[1].push(object_ptr1);

and trust that the two object pointers have been ordered correctly in the priority_queue?

Thanks


What is "compare"? If it's a function pointer, you must be very careful to not use it before you supply a value, as the default constructed priority_queue will use a null pointer. The easiest way to ensure non-null pointers – if you cannot rewrite or wrap as shown below – is, ironically, to never use the index operator; instead use the find and insert methods.

If "compare" is instead a functor, then it should be written so its default construction does exactly what's needed (often nothing) – it is very rare for this to not be possible.

Once the comparator in the priority_queue has a proper value (e.g. not a null pointer in the pointer case), then you can be sure your objects will be ordered correctly.


If you have a fixed function and are using function pointers:

bool my_compare(object_t *a, object_t *b) {
  // do something
}
typedef bool (*compare)(object_t*, object_t*);

Rewrite to:

struct compare {
  bool operator()(object_t *a, object_t *b) {
    // do something
  }
};

If you cannot rewrite the function to be a comparator (e.g. it's from some third-party library), you can wrap a (fixed) function pointer in a comparator:

bool my_compare(object_t*, object_t*);
struct compare {
  bool operator()(object_t *a, object_t *b) {
    return my_compare(a, b);
  }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号