1

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.

4
  • 1
    why isn't scanning from start to finish and finding the max ok? Commented Aug 20, 2014 at 15:10
  • Because there is a value in the dataset that is an error code for something else that I would like to ignore for this calculation. Commented Aug 20, 2014 at 15:11
  • e.g find max but ignore all values of 55505. Obviously I can iterate just wondering if there is an simple method considering its only one value. Commented Aug 20, 2014 at 15:12
  • 1
    Use std::max_element with a (lambda) function comp to tell if a value is bigger than another. Implement it, such that e.g. 55505 is the smallest element. Commented Aug 20, 2014 at 15:14

1 Answer 1

5

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I would move rhs test first to satisfy (t < t) == false.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.