who could explain more about the compare function in priority queue C++ -


we define operator < people seem use class define operator ()?

how work.

i have learned generic thing in c before, @ time, use pointer function.

what difference?

basically, want code contain least amount of surprises.

let's have std::priority_queue<t> pq class t. t class natural ordering exists? if so, define operator < it. want pq prioritised based on ordering? if so, let use operator < , you're done.

however, quite often, t class no intrinsic notion of ordering. imagine class employee storing name, startingdate , salary. there no universal ordering - given 2 employees, it's not clear 1 < other.

at same time, may want std::priority_queue<employee> based on earns most. or least. or who's company longest. therefore, you'll use specific comparators these.

in way, priority queue comparator , operator < independent concepts. if have naturally orderable class, give operator <. if want priority queue, give appropriate predicate. if predicate happens operator <, let use that.

as why use class operator() instead of pointer function, i'd primary reason typing , construction. class templates use comparators (such std::priority_queue or std::map) have type of comparator template parameter (they have no other option). then, when constructing container, have 2 options: provide object of comparator type, or let class create 1 default construction.

when type of comparator class (with default constructor, present these functor classes), constructor of std::priority_queue can default-construct , work. if use function pointer, type of queue e.g. std::priority_queue<t, somecontainer, bool (*)(const t&, constt&)>, , have pass appropriate function pointer each queue create.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -