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 ) ;
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 ) ;
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;
}
You can use max_element
#include <iostream>
#include <vector>
#include <algorithm>
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<<endl;
//get max
val = max_element(first,last);
cout<<"Max val is "<<*val<<endl;
return 0;
}
You can use max_element
#include <iostream>
#include <vector>
#include <algorithm>
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<<endl;//get max
val = max_element(first,last);
cout<<"Max val is "<<*val<<endl;return 0;
}
You don't need #include <vector> and the variable start.
Leave off the -1 after len and it will work. Nice code!
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.
Why didn't you stay with the vector? Pushing the numbers into a vector and then ...
cout << "Min val is " << *min_element(v.begin(),v.end()) << endl;
cout << "Max val is " << *max_element(v.begin(),v.end()) << endl;
... would sound easier to me.
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.