Search code examples
c++stable-sort

stable_sort in C++


Im trying to use stable_sort in order to sort a vector of pointers

to a certain class. I've a code like this :

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class B
{
    public :
        B(int y, int j) {x = y, r = j;};

        void getVal() {cout << x << endl; };

        int x;
        int r;
};


bool compareB(B* b1, B* b2)
{
    return b1->getVal() < b2->getVal();
}

int main()
{
    B b1(3, 4), b2(-5, 7), b3(12, 111);

    vector<B*> myVec;
    myVec.push_back(&b1);
    myVec.push_back(&b2);
    myVec.push_back(&b3);

    std::stable_sort(myVec.begin(), myVec.end(), compareB);
    for (size_t size = 0; size < myVec.size(); ++size)
    {
        myVec[size]->getVal();
    }

    return 0;
}

However, I get the foolowing error while compiling it :

"error: invalid operands of types 'void' and 'void' to binary 'operator<' return b1->getVal() < b2->getVal();"

Can someone help me ?


Solution

  • The problem is with

    void getVal() {cout << x << endl; };
    

    It returns void instead of some value.

    When you use it in return b1->getVal() < b2->getVal(); it boils down to return void < void; which will not compile.

    You should be able to change it to

    int getVal() { return x; };