In a related question, I asked how to get the value of the max element in a vector of objects in c++ based o some field of said objects. I extended the algorithm to get the index of that max element so I could later just pop it from the vector of object.
Here is the code that I use right now and it works fine:
vector<MyOwnClass> scoretracker // MyOwnClass has a ".score" field
// Some code filling scoretracker
auto max = std::max_element(scoretracker.begin(), scoretracker.end(),
[] (const MyOwnClass &a, const MyOwnClass &b )
{
return a.score < b.score; // I am not sure how this line works
});
int index = distance(scoretracker.begin(), max);
So, I tried to modify this to get the second highest (or n-th value) instead of the max but so far my attempts failed.
It makes me realize that I don't really understand why "return a.score < b.score" returns the highest value.
By looking at how max_element works, I am not sure if it could ever be used to find the 2nd largest.
Oh, finally, I would rather not pop_back the highest value from the vector, find the new max (the 2nd highest value in the original vector) and add some logic to restore the original version. Well if I have to, I'll do it but there might be some iterator property or something else I don't know...