Programming Challenge

Ron Guilmette rfg at NCD.COM
Sat Dec 22 16:25:12 AEST 1990


In article <1990Dec15.015355.15683 at fmrco> harold at fmrco (Harold Naparst) writes:
>
>I am trying to write a function which will return the index
>of the smallest element of an array.  I want the routine
>to work for any type array.  That is, I don't want to write
>a separate routine for each type of array (real or double or
>integer).  How can I do this ?  I tried playing around with 
>the GNU C typeof operator, but couldn't figure it out.  Any ideas ?



I see that there have been a few responses to this already, but I didn't
see anyone actually give what I consider to be a `good' answer.

The question was how to "write" a generic function to find the index of
the smallest element of an array of an arbitrary type.  The questioner
did not say anything about actually needing to compile it into executable
code with the help of any currently available C++ language processor.
:-) :-) :-)

Here is a solution:


template<class T> unsigned smallest (T array[], unsigned array_size)
    throw (Range_Error)
{
  T* smallest_value_p = &array[0];
  unsigned smallest_index = 0;

  if (array_size == 0)
    throw Range_Error (Zero_Length);

  for (unsigned i = 1; i < array_size; i++)
    if (array[i] < *smallest_value_p)
      {
	smallest_value = &array[i];
	smallest_index = i;
      }

  return i;
}

Won't life be beautiful when we can actually *use* templates & exceptions?

-- 

// Ron Guilmette  -  C++ Entomologist
// Internet: rfg at ncd.com      uucp: ...uunet!lupine!rfg
// Motto:  If it sticks, force it.  If it breaks, it needed replacing anyway.



More information about the Comp.lang.c mailing list