T0maas
T0maas

Reputation: 412

Find max value in std::vector of structure of specified variable

I have vector of structure described below:

struct Point {
    double x,y;
};

And now I have vector<Point> which contains about 2000 elements. I want to find element which contains maximum value of variable y in Point.

I know there is std::max_element but I don't know if it works with variables stored in structures inside vector.

Upvotes: 1

Views: 1809

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122468

I don't know if it works with variables stored in structures inside vector.

Yes it does. Use a custom comparator:

auto it = std::max_element(v.begin(),
                           v.end(),
                           [](const auto& a,const auto& b) { 
                               return a.y < b.y; 
                           });

Upvotes: 3

Related Questions