0
enum class comp {
    age,
    weight
};
struct person {
    int age;
    int weight;
    static auto max(std::vector<person> x, comp(y)) {
        if (comp(y) == comp::age) {
            for (person e : x) {
                auto max = 0;
                for (card e : x) {
                    if (max < e)
                        max = e;
                }

            }
        }

i am trying to find the max value of age, weight from this vector of a struct construction.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

3 Answers3

1

You can use std::max_element with a lambda instead

#include <algorithm>

auto it_max = std::max_element(x.begin(), e.end(), [](auto const& lhs, auto const& rhs) {
    return lhs.age < rhs.age;  // or whatever you want to compare
}

Then it_max is a std::vector<person>::iterator referring to the max person in the vector x based on your comparison criteria. If you want to compare multiple fields in each struct you could use something like std::tie just make sure your comparison function satisfies "strict weak ordering".

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

here is a corrected version of your code. As cory post shows you can do this with standard algorithms in a much cleaner way

struct person {
    int age;
    int weight;
    static int max(std::vector<person> x, comp y) {
        if (y == comp::age) {
            for (person e : x) {
                auto max = 0;
                for (auto e : x) {
                    if (max < e.age)
                        max = e.age;
                }
               return max;
            }
        }
        return 0;
    }
};
int main()
{
   person p1;
   person p2;
   p1.age=42;
   p2.age=4;
   std::vector<person> pp{p1,p2};
   int maxAge = person::max(pp, comp::age);

}
pm100
  • 48,078
  • 23
  • 82
  • 145
1

Pay attention to that the user can pass an empty vector. In this case to return an object of the type person does not make a sense.

It is better to return an iterator that points to the maximum element or the last iterator of the range of elements of the vector in case when the vector is empty.

You can use the standard algorithm std::max_element the following way

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

enum class comp {
    age,
    weight
};

struct person {
    int age;
    int weight;

    static auto max( const std::vector<person> &v, comp cmp ) 
    {
        return std::max_element( std::begin( v ), std::end( v ),
            [=]( const auto &p1, const auto &p2)
            {
                return cmp == comp::age ? p1.age < p2.age
                                        : p1.weight < p2.weight;
            } );
    }               
};
//...
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335