note, I am not asking for answers. I simply am curious regarding why things work
I need to implement a priority queue for a printer simulator for a class assignment. After looking at examples on the internet, I noticed that operator< was being overloaded in order to arrange the priority queue correctly.
code in question: java2s priority queue example
Why does operator< need to be overloaded? Where is ‘<‘ even used to make the comparison? Does implementing the operator overload change the way the queue STL works?
This implementation doesn’t seem intuitive to me at all: why isn’t operator> being overloaded instead? How is one supposed to learn that operator< needs to be overloaded in order for the priority_queue to work correctly?
STL containers use operator< by default to order the contents, for those containers that order the contents.
You can override this by passing in a comparison functor to the constructor of the container, which allows you to decouple the sorting/ordering from the container object.
Operator> could have been chosen, but one had to be picked and that was operator<, and is then used everywhere for consistency.