max_element

S

Stephen Howe

Hi

If I had

vector<int> v;

I can do

if (!v.empty())
{
const int vmax = *max_element(v.begin(), v.end());
// further stuff with vmax
}

and this works. But suppose I had

struct compound
{
int a;
int b;
};

vector<compound> w;

I would like to do

if (!w.empty())
{
const int wmaxa = *max_element(w.begin(), w.end()); // max a
value
const int wmaxb = *max_element(w.begin(), w.end()); // max b
value

}

Thinking aloud, I presume I use the predicate version, pass different
predicates, dereference and take the a & b values, yes?

Thanks

Stephen Howe
 
V

Vladimir Jovic

Stephen said:
Hi

If I had

vector<int> v;

I can do

if (!v.empty())
{
const int vmax = *max_element(v.begin(), v.end());
// further stuff with vmax
}

and this works. But suppose I had

struct compound
{
int a;
int b;
};

vector<compound> w;

I would like to do

if (!w.empty())
{
const int wmaxa = *max_element(w.begin(), w.end()); // max a
value
const int wmaxb = *max_element(w.begin(), w.end()); // max b
value

}

Thinking aloud, I presume I use the predicate version, pass different
predicates, dereference and take the a & b values, yes?


http://www.cplusplus.com/reference/algorithm/max_element/

In the comparison function (or functor), you can do whatever comparison
you like. To find wmaxa you can implement a comparison function to take
two compound structure objects, but compare only a fields.
 
A

Armen Tsirunyan

Hi

If I had

vector<int> v;

I can do

if (!v.empty())
{
    const int vmax = *max_element(v.begin(), v.end());
    // further stuff with vmax

}

and this works. But suppose I had

struct  compound
{
      int a;
      int b;

};

vector<compound> w;

I would like to do

if (!w.empty())
{
    const int wmaxa = *max_element(w.begin(), w.end());    // max a
value
    const int wmaxb = *max_element(w.begin(), w.end());    // max b
value

}

Thinking aloud, I presume I use the predicate version, pass different
predicates, dereference and take the a & b values, yes?

Thanks

Stephen Howe

Yes, exactly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top