Archived

This topic is now archived and is closed to further replies.

C++ Question

This topic is 5972 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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!]

Share this post


Link to post
Share on other sites
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 element


int minVal = *min;
int Index = min-list; //index of element



Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.)

Share this post


Link to post
Share on other sites