sort使用自定义排序函数对vector进行排序时报错invalid operator <
struct MyStruct {
int val;
int port;
};
bool Compare(const MyStruct *a, const MyStruct *b)
{
if (a->val > b->val) {
return true;
}
if (a->port > b->port) {
return true;
}
return false;
}
std::vector<MyStruct *> m_vec;
sort(m_vec.begin(), m_vec.end(), Compare);
以上代码报错invalid operator <。
原因:使用排序函数进行排序时必须是严格弱序比较,也就是要严格定义<,val的值相等时,没有遵循严格比较,导致问题,对比函数修改如下
bool Compare(const MyStruct *a, const MyStruct *b)
{
if (a->val > b->val) {
return true;
} else if (a->val == b->val) {
if (a->port > b->port) {
return true;
} else if (a->port == b->port) {
return true;
} else {
return false;
}
}
}