[C++] Using std::max_element on a vector of pairs
Go to solution
Solved by Shoob,
1 hour ago, as96 said:The code you wrote doesn't look wrong at all, and should work perfectly and as far as performance goes I don't see any major issue, however if you HAVE to use the algorithm library for whatever reason you can use the sort function:
http://www.cplusplus.com/reference/algorithm/sort/
and write a function like this to pass to the sort method:
bool myfunction (int prod1, int prod2) { return (prod1.GetPrice() < prod2.GetPrice()); }Then take the last item in the vector.
PS: max_element would work in the same way.
Thanks! I didn't think of using another method.
After tinkering with it I came to the conclusion that it's practical to use a lambda expression based on the method you suggested.
Here's the code I wrote if anyone has a similar problem in the future:
Product Client::GetMostExpensiveProduct() { auto mostExpensive = max_element(cProducts.begin(), cProducts.end(), [](pair<Product, int>& prod1, pair<Product, int>& prod2) { return (prod1.first.GetPrice() < prod2.first.GetPrice()); }); return mostExpensive->first; }
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now