Differences
This shows you the differences between two versions of the page.
Both sides previous revision Previous revision | |||
coding_cheat_sheet [2021/10/03 20:44] paul [Max Heap with Pairs] |
coding_cheat_sheet [2021/11/08 00:09] (current) paul [Using Custom Data With Priority Queues] |
||
---|---|---|---|
Line 259: | Line 259: | ||
==== Using Custom Data With Priority Queues ==== | ==== Using Custom Data With Priority Queues ==== | ||
- | There are numerous was of doing this but here is the least verbose | + | There are numerous was of doing this but here is the most elegant |
+ | |||
+ | <code cpp> | ||
+ | struct node{ | ||
+ | node(int id, int value) : id(id), value(value){} | ||
+ | int id; | ||
+ | int value; | ||
+ | }; | ||
+ | |||
+ | auto cmp = [](const node &a, const node &b){ | ||
+ | //Max Heap: | ||
+ | // | ||
+ | //larger b will appear later in the container and therefore have a higher priority | ||
+ | return a.value < b.value; | ||
+ | |||
+ | //MIN Heap: | ||
+ | //if a is larger than b, it will appear before b, so smaller b will have higher priority | ||
+ | return a.value > b.value; | ||
+ | }; | ||
+ | |||
+ | priority_queue< | ||
+ | </ | ||
+ | |||
+ | A less elegant way of overloading the default less than operator is as follows: | ||
<code cpp> | <code cpp> | ||
Line 266: | Line 289: | ||
int id; | int id; | ||
int value; | int value; | ||
- | } | + | }; |
bool operator< | bool operator< |