user695652
user695652

Reputation: 4275

Minimum element in empty array

If you have a function int getMin(int a[], int n) then what would you say is the cleanest solution to deal with the empty array case?

Upvotes: 2

Views: 1482

Answers (4)

Mark B
Mark B

Reputation: 96241

Maybe instead, do it the way the standard library does: Take two iterators as parameters and return the end parameter if the sequence is empty. Better still use min_element instead of rolling your own.

If you need to do it the array/length way either throw or return std::numeric_limits<int>::max()

Upvotes: 3

Ted Hopp
Ted Hopp

Reputation: 234795

There is definitely no "cleanest solution" absent an understanding of the domain. Mathematically, the infimum of any set of values from a domain is the greatest lower bound (in the domain) of all elements of the set. For the extended integers, this would be +infinity for an empty set. (See, e.g., the Wikipedia article on Empty Set) If your domain is all C++ int values, a (mathematically consistent) return value would then be INT_MAX.

Upvotes: 1

Billy ONeal
Billy ONeal

Reputation: 106530

Return a pointer to the minimum element instead of the element itself. This way, a pointer value of one past the end of the array can indicate not found. (Or in this case empty)

This is the strategy taken by std::min_element, which already implements what you're doing.

You can even implement this in terms of std::min_element:

int* getMin(int a[], int n)
{
    return std::min_element(a, a+n);
}

Upvotes: 12

Assuming you're looking for the minimum value in the array how about:

if (!n)
  throw YourPreferredException();

Or:

#include <limits>
//...
if (!n)
  return std::numeric_limits<int>::max();

Or, if it should never happen:

#include <cassert>
//...
assert(n);

It depends on the application and the values you're expecting to be passing in. What makes most sense and what fits the existing code base is hard to guess.

Upvotes: 3

Related Questions