Over my programming career I formed a habit to introduce a flag variable that in
ID: 642515 • Letter: O
Question
Over my programming career I formed a habit to introduce a flag variable that indicates that the first comparison has occured, just like Msft does in its linq Max() extension method implementation
public static int Max(this IEnumerable<int> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
int num = 0;
bool flag = false;
foreach (int num2 in source)
{
if (flag)
{
if (num2 > num)
{
num = num2;
}
}
else
{
num = num2;
flag = true;
}
}
if (!flag)
{
throw Error.NoElements();
}
return num;
}
However I have met some heretics lately, who implement this by just starting with the first element and assigning it to result, and oh no - it turned out that STL and Java authors have preferred the latter method.
Java:
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) > 0)
candidate = next;
}
return candidate;
}
STL:
template<class _FwdIt> inline
_FwdIt _Max_element(_FwdIt _First, _FwdIt _Last)
{ // find largest element, using operator<
_FwdIt _Found = _First;
if (_First != _Last)
for (; ++_First != _Last; )
if (_DEBUG_LT(*_Found, *_First))
_Found = _First;
return (_Found);
}
Are there any preferences between one method or another? Are there any historical reasons for this? Is one method more dangerous than another?
Explanation / Answer
to be totally radical you can do:
public static int Max(this IEnumerable<int> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
int num = int.MinValue;
foreach (int num2 in source)
{
if (num2 > num)
{
num = num2;
}
}
return num;
}
by defining the max of a empty set to be int.Minvalue
but it is possible to do the java/stl approach with c#
public static int Max(this IEnumerable<int> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if(!source.MoveNext()){
throw throw Error.NoElements();
}
int num = source.Current;
foreach (int num2 in source)
{
if (num2 > num)
{
num = num2;
}
}
return num;
}
though YMMV whether it's clearer or not
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.