I have three random-access iterators parent
, child1
, and child2
, which point to certain values in a permuted array. (Context: I'm implementing heapsort; those iterators comprise a binary subtree).
I need to determine the iterator, which has the largest referenced value (to maintain the max-heap property of the heap). So, if *parent
is the largest, return parent
, if *child1
is the largest, return child1
, etc.
Pseudocode:
#include <algorithm>
auto iterator = std::max({ parent, child1, child2 });
iterator
is now the iterator whose underlying value is the greatest.
The problem is that using this literal pseudocode, std::max
would compare the iterators itsself here, not their referenced values. I could do std::max({ *parent, *child1, *child2 })
, but it returns decltype(*parent)
, so how would I get the iterator back from there?
I know it's trivially feasible using some if
s, but isn't there some more elegant way? Does the standard library have something there? I tried several things, but they all seem bulky and inconvenient.
If you don't consider std::max
with a custom comparator bulky, here it is:
auto iterator = std::max({ parent, child1, child2 },
[](auto it_a, auto it_b) { return *it_a < *it_b; });