Sort a list based on attributes of objects

Hello everyone,
I have started learning CPP very recently. Sorry if the question is naive. Suppose I have indexes to the list of courses a student (from class of students)has failed. Now I want to sort that index list based on the student test results. How should I do that? here is an example:

s.failed_courses_index=[1,3,5,7];
s.course[1].result=10;
s.course[3].result=15;
s.course[5].result=9;
s.course[7].result=12;

Sort the "s.failed_course_index" based on the "s.course[i].result" so that

s.failed_coursed_index= [5,1,7,3];

Can you use std::sort?
In addition to trying to use std::sort, it might help if you showed actual an C++ code framework that could be worked off of.
Sorting depends on a question: "Should x be before y?"

Should index 3 be before index 5? No.
Should index 5 be before index 7? Yes.

You obviously cannot use simple 3 < 5, 5 < 7.

However, if you can expand x < y
into s.course[x].result < s.course[y].result
then you have the Question.

See http://www.cplusplus.com/reference/algorithm/sort/
That algorithm does sort ranges and does take the Question as a parameter.

C++11 did introduce lambda closures. A syntax for in-place functions.
https://en.cppreference.com/w/cpp/language/lambda

1
2
3
4
std::sort( std::begin(s.failed_courses_index),
           std::end(s.failed_courses_index),
           [&s](int x, int y) { return s.course[x].result < s.course[y].result; }
          );
Thanks for the responses. @keskiverto, your response was the closest one, I was looking for.
Topic archived. No new replies allowed.