C++ 类指针向量上的std::sort()
我有一个类指针向量C++ 类指针向量上的std::sort(),c++,sorting,stl,stl-algorithm,C++,Sorting,Stl,Stl Algorithm,我有一个类指针向量std::vector listSquares。我想用类的一个属性作为键对它进行排序。这就是我正在做的 bool compById(Square* a, Square* b) { return a->getId() < b->getId(); } std::sort(listSquares.begin(), listSquares.end(), compById) bool compById(正方形*a,正方形*b) { 返回a->getId()g
std::vector listSquares
。我想用类的一个属性作为键对它进行排序。这就是我正在做的
bool compById(Square* a, Square* b)
{
return a->getId() < b->getId();
}
std::sort(listSquares.begin(), listSquares.end(), compById)
bool compById(正方形*a,正方形*b)
{
返回a->getId()getId();
}
排序(listSquares.begin()、listSquares.end()、compById)
但编译器说:
错误:调用“sort(std::vector::iterator,std::vector::iterator,)时没有匹配的函数
这里我做错了什么?您缺少的最重要的部分是compare函数的参数是
const
。另一个是返回类型。如果在声明函数时省略了返回类型,编译器将假定它返回int
,这在本例中是不正确的
当然,当您调用
std::sort
函数时,比较函数必须在范围内。为了使用compById
作为std::sort
的参数,它不应该是成员函数。这是错误的
class Square
{
bool compById(Square* a, Square* b)
{
return a->getId() < b->getId();
}
...
};
classsquare
{
布尔康比ID(正方形*a,正方形*b)
{
返回a->getId()getId();
}
...
};
这样比较好,
class Square
{
...
};
bool compById(Square* a, Square* b)
{
return a->getId() < b->getId();
}
classsquare
{
...
};
布尔康比ID(正方形*a,正方形*b)
{
返回a->getId()getId();
}
您可以使用成员函数。但是您需要将其定义为静态成员函数,并从类而不是类的实例调用它
请注意,函数声明前的static
,以及排序中函数名前的Square::
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);
}
classsquare
{
/*...*/
公众:
静态布尔compById(常数平方*a,常数平方*b)
{
返回a->getId()getId();
}
};
main()
{
/*...*/
std::sort(listSquares.begin()、listSquares.end()、Square::compById);
}
如果你能使用C++11,你应该把它设为lambda:std::sort(listSquares.begin(),listSquares.end(),[](Squares*a,Squares*b){return a->getId()getId;})
。确保你确实需要指针,而不仅仅是对象。我不能使用C++11@chris我确定我想使用指针。@qutab您在类内部还是外部声明了compById?它应该在外部。@john,我已经在类内部声明它为私有成员函数。即使我使用const,我也会得到同样的错误。在本例中,我还得到了gameplay.cpp:911:error:将'const Square'作为'int Square::getId()'的'this'参数传递会丢弃限定符[-fppermissive]@qutab,您也必须使getId()成为const成员函数。非常感谢。这就是问题所在。但是为什么我们不能将它声明为成员函数呢?实际上,我在一个不同于square本身的类中使用它,因为std::sort在调用成员函数时如何知道要使用哪个对象?只能对对象调用成员函数,但std::sort没有上下文来确定应该是哪个对象。假设您是从某个对象内部调用std::sort,但并没有将该对象传递给std::sort。sort不知道从何处调用它,它只知道传递给它的三个参数。它可以是一个静态成员函数。普通(非静态)成员函数采用隐式第一个参数,即“this”,因此具有与非成员函数不同的签名。