C++ Question

Started by
3 comments, last by Sudie 22 years, 8 months ago
Is there a function that determines the lowest element (meaning that which has the lowest value) of a group of integers (which I guess would be in an array). I''ve tried using min_element from the algorithm.h, but I didn''t have much success with that. If so, an example would be nice too. Thanks for your help in advance.
Advertisement
That''s pretty east to write:
  int lowest_value(int *array, unsigned int max) {  int lowest = *array;  while( --max > 0 ) {    array++;    if(*array < lowest) lowest = *array;  }  return lowest;}unsigned int lowest_index(int *array, unsigned int max) {  unsigned int lowest = 0, at;  for(at = 1; at < max; at++) {    if(array[at] < array[lowest]) lowest = at;  }  return lowest;}  


[Resist Windows XP''s Invasive Production Activation Technology!]
min_element should do just fine : What you have to understand, it that it uses iterator and returns an iterator. The nice thing is pointers are iterator.

Here is how to use min_element :

  const int SIZE = 4;int list[SIZE];//put values in list;int* min = std::min_element( list, list+SIZE);//min now points to the smallest elementint minVal = *min;int Index = min-list; //index of element  


How would you do it if it was based on user input until the user inputs a 0 or a negative number?

Edited by - Sudie on August 8, 2001 5:39:52 PM
The only difference would be that ''size'' would be however many elements you read in, not the size of the array. (Be sure to ensure that you don''t read in too many elements for the array, though.)

This topic is closed to new replies.

Advertisement