Search code examples
c++classcomparatorheapsort

Heap sorting vector of Clients, passing iterators incorrectly?


I am working on a program that creates a vector of 4 Clients, then heap sorts them using a comparator class (sorting by their account balance essentially). After that I'm simply printing out the ordered account numbers of each Client in the vector. However, I don't think I have it implemented correctly. Firstly, when I call the STL heap sort on the vector, I understand that I pass the comparator as the third argument. I was under the impression that I needed to call it with an object of my AccountOrder comparator class, but that gave me a large number of errors. If I call it on the Class and not an instance of that class, it doesn't give me nearly as many errors. What is the correct way to do this?

int main()
{
    AccountOrder f;

    vector<Client> list;

    Client client1(345.88, "Charlie");
    Client client2(249.12, "Rashesh");
    Client client3(442.90, "Michael");
    Client client4(543.74, "Mary");

    list.push_back(client1);
    list.push_back(client2);
    list.push_back(client3);
    list.push_back(client4);

    make_heap(list.begin(), list.end(), f);
    sort_heap(list.begin(), list.end(), f);

    for(int i = 0; i < list.size(); i++) 
        cout << list[i].getAccountBalance();

    system("pause");
    return 0;
}

Comparator class:

class AccountOrder 
{
    public:
    bool operator()(Client * a, Client * b) 
    {
        return a->getAccountBalance() > b->getAccountBalance();
    };
};

The comparator has been implemented in my code just above the main() function. Secondly, which function do I actually need to pass the comparator to? (Here I've passed it to both, I'm not sure yet).


Solution

  • Make comparator with & instead of *

    class AccountOrder 
    {
        public:
        bool operator()(const Client &a, const Client &b) const
        {
            return a.getAccountBalance() > b.getAccountBalance();
        };
    };
    

     

    Permake_heap and sort_heap:

    The signature of the comparison function should be equivalent to the following:

    bool cmp(const Type1 &a, const Type2 &b);

    The signature does not need to have const &, but the function must not modify the objects passed to it.