kami kami - 1 year ago 99
C++ Question

Sorting a vector inside a custom class C++ using std::sort

How do I sort two vectors inside a custom class using std::sort?

As an example, let's say I have a class containing two vectors, ids and marks. After initializing the vectors, I would like to sort the elements of this class by marks, preserving the sorted order in the ids.

I've attempted to do this using the custom


class Example
void init();
static bool sortByMarks(const Example &lhs, const Example &rhs);
//....other functions

vector<int> ids;
vector<int> marks;
//....other variables
void Partition::init()
for(int i=0;i<5;i++)
bool Partition::sortByMarks(const Example &lhs, const Example &rhs);
return lhs.marks < rhs.marks;

EDIT: [This is fixed by adding the Example:: to the function call] I'm having trouble calling this function. I tried the following:

Example e;
sort(&e, &e, Example::sortByMarks);

Sample Input:

ids : 1,2,3,4,5
marks: 47,44,88,52,46

Sample Output:

ids : 2,5,1,4,3
marks: 44,46,47,52,88

Any help is appreciated!

EDIT: Marks vector is what I want sorted (ids should also be changed accordingly)

Answer Source

I don't think you can do it with vectors like that. You need to couple ids with marks somehow, e.g using map, vector of pairs or like this:

class Example{
    void init();
    void sortByMarks();

    struct Students{
        int ids;
        int marks;
    std::vector < Students > students;


void Example::sortByMarks(){
    std::sort(students.begin(), students.end(), [](Students a, Students b){
        return a.marks < b.marks;

int main(){
    Example e;

Or you could write your own sort:

void selection_sort(){
    int size = marks.size();
    for (int i = 0; i < size - 1; i = i + 1){
        int min = i;
        for (auto j = i + 1; j < size; j = j + 1){
            if (marks[j] < marks[min]){ min = j; }
        std::swap(marks[i], marks[min]);
        std::swap(ids[i], ids[min]);    // add this extra line
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download