954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How can i find out the Max and Min value from a Vector?

How can i find out the Max and Min value from a Vector, what's the function can i use to do that?

max_find()
e.g.

double x[];
double x_max;
double x_min;


x_max = max_find( x );
x_min = min_find ( x ) ;

see_moonlight
Newbie Poster
7 posts since Oct 2004
Reputation Points: 10
Solved Threads: 0
 

Don't know if there is a function built-in off the top of my head but it would be so easy to just write your own.

double max_find()
{
double max = 0; // This may need to be initalised different base on your data
for (int i = 0; i < x.size(); i++)
{
if (max < x.at(i)) max = x.at(i);
}
return max;
}

jasweb2002
Junior Poster in Training
56 posts since Sep 2004
Reputation Points: 11
Solved Threads: 2
 

You can use max_element


#include
#include
#include
using namespace std;
int main(int)
{
const int len = 3;
const int start = 0;
double arr[len];
arr[0]= 2.4;
arr[1] = 1.2;
arr[2] = 3.67;

double* first = arr;
double* last = arr + len - 1;

//get min
double* val = min_element(first,last);
cout<<"Min val is "<<*val<

britt_boy
Newbie Poster
13 posts since Dec 2004
Reputation Points: 10
Solved Threads: 1
 

You can use max_element

#include #include #include using namespace std; int main(int) { const int len = 3; const int start = 0; double arr[len]; arr[0]= 2.4; arr[1] = 1.2; arr[2] = 3.67; double* first = arr; double* last = arr + len - 1; //get min double* val = min_element(first,last); cout<<"Min val is "<<*val< You don't need #include and the variable start. Leave off the -1 after len and it will work. Nice code!

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

My mistake. I originally wrote it using a vector then realized i could convert it to use an array, then forgot about .end() for the array.

britt_boy
Newbie Poster
13 posts since Dec 2004
Reputation Points: 10
Solved Threads: 1
 

Why didn't you stay with the vector? Pushing the numbers into a vector and then ...
[php]
cout << "Min val is " << *min_element(v.begin(),v.end()) << endl;
cout << "Max val is " << *max_element(v.begin(),v.end()) << endl;
[/php]
... would sound easier to me.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

Yep better and easier to use vector. The orig post referred to an array so i thought i would be strict and stick with that.

britt_boy
Newbie Poster
13 posts since Dec 2004
Reputation Points: 10
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You