简体   繁体   中英

std::sort() on a vector of Class pointers

I have a vector of class pointers std::vector<Square*> listSquares . I want to sort it with one of the attributes of the class as the key. This is what I'm doing

bool compById(Square* a, Square* b)
{
    return a->getId() < b->getId();
}

std::sort(listSquares.begin(), listSquares.end(), compById)

but the compiler says: error: no matching function for call to 'sort(std::vector::iterator, std::vector::iterator, <unresolved overloaded function type>)'

what am I doing wrong here?

In order to use compById as a parameter to std::sort it should not be a member function. This is wrong

class Square
{
    bool compById(Square* a, Square* b)
    {
        return a->getId() < b->getId();
    }
    ...
};

This is better,

class Square
{
    ...
};

bool compById(Square* a, Square* b)
{
    return a->getId() < b->getId();
}

The most important part you're missing is that the arguments to the compare function are const . Another is the return type. If you leave out the return type when declaring a function, the compiler will assume it returns int which is not correct in this case.

And of course the comparison function has to be in scope when you call the std::sort function.

You can use a member function. But you need to define it as a static member function and call it from the class, not an instance of the class.

Notice static before the function declaration, and Square:: before the function name in sort.

class Square
{
    /*...*/
public:
    static bool compById(const Square* a, const Square* b)
    {
        return a->getId() < b->getId();
    }
};

main()
{
    /*...*/
    std::sort(listSquares.begin(), listSquares.end(), Square::compById);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM