I am using some data that uses some an extremely high value as an error code. I am currently using std max element, is there a way to do this ignoring a particular value?. eg max element that isant a particular number.
1 Answer
So, let's use a custom comparator as part of the call to std::max_element. We'll just make sure that if we see the error code, then we'll make that smaller than all other elements.
auto maxElement = std::max_element(std::begin(container), std::end(container), [](T const & lhs, T const & rhs) -> bool {
if (rhs == error_code)
return false;
if (lhs == error_code)
return true;
return lhs < rhs;
}
2 Comments
Jarod42
I would move
rhs test first to satisfy (t < t) == false.Bill Lynch
@Jarod42: I was thinking about if we'd need a case for
lhs == rhs == error_code but that should cover it as well. Good idea.
std::max_elementwith a (lambda) functioncompto tell if a value is bigger than another. Implement it, such that e.g. 55505 is the smallest element.