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
0
Newbie Poster

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 ) ;

Jump to PostYou 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 …

Jump to PostMy 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.

jasweb2002
0
Junior Poster in Training

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;

}

britt_boy
0
Newbie Poster

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;

}

Dave Sinkula
commented:
Use code tags.
+0

vegaseat
1,735
DaniWeb's Hypocrite
Team Colleague

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!

britt_boy
0
Newbie Poster

vegaseat
1,735
DaniWeb's Hypocrite
Team Colleague

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.

britt_boy
0
Newbie Poster

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.