kami kami - 2 months ago 13
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

std::sort
function.

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

private:
vector<int> ids;
vector<int> marks;
//....other variables
}
void Partition::init()
{
ids.resize(5);
marks.resize(5);
for(int i=0;i<5;i++)
ids[i]=i+1;
marks[0]=47;marks[1]=44;marks[2]=88;marks[3]=52;marks[4]=46;
}
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

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{
public:
    void init();
    void sortByMarks();

private:
    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;
    e.sortByMarks();
}

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
    }
}