C++ examples for STL Algorithm:max_element
Finding the maximum element for user-defined types
#include <algorithm> #include <vector> #include <iostream> using namespace std; struct Person {//from w w w.ja v a 2 s.c o m Person(const char* name, int rating): name_(name), rating_(rating) {} const char* name_; int rating_; }; struct IsWeakerPlayer { bool operator()(const Person& x, const Person& y) { return x.rating_ < y.rating_; } }; int main() { Person p1("G", 5); Person p2("V", 7); Person p3("A", 8); vector<Person> v; v.push_back(p1); v.push_back(p2); v.push_back(p3); cout << "the best player is " << max_element(v.begin(), v.end(), IsWeakerPlayer())->name_; cout << endl; }