开发者

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?


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);
}


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.


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()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜