类指针向量上的 std::sort() [英] std::sort() on a vector of Class pointers
本文介绍了类指针向量上的 std::sort()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类指针向量 std::vector
.我想用类的属性之一作为键对其进行排序.这就是我正在做的
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)
但是编译器说:错误:没有匹配的函数调用'sort(std::vector::iterator, std::vector::iterator, <unresolved重载函数类型>)'
but the compiler says: error: no matching function for call to 'sort(std::vector::iterator, std::vector::iterator, <unresolved overloaded function type>)'
我在这里做错了什么?
推荐答案
为了使用 compById
作为 std::sort
的参数,它不应该是成员功能.这是错误的
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();
}
...
};
这样更好,
class Square
{
...
};
bool compById(Square* a, Square* b)
{
return a->getId() < b->getId();
}
这篇关于类指针向量上的 std::sort()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文