gpt4 book ai didi

c++ - "invalid comparator": error when overloading the "<" operator

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:53 26 4
gpt4 key购买 nike

我有一个类需要排序。使用此类的 vector ,排序时出现“无效比较器”错误。

我在我的类中重载了“<”运算符并遵循严格的弱排序

如本post所述.

sort 需要严格的弱排序。你的 comparator 不是一个。除其他事项外,对于严格的弱排序,comp(x, x) 必须为 false

这是我的代码:

bool outlierScore::operator<(const outlierScore& other) {
if (score < other.score)
return score < other.score;
else if (coreDistance < other.coreDistance)
return coreDistance < other.coreDistance;
else if (id < other.id)
return id < other.id;
else
return false;
}

这是重载的运算符函数,它所做的本质上是尝试按离群值分数升序排序,核心距离用于打破离群值关系,以及用于打破核心距离关系的 ID。

Stack Trace 揭示了这个阶段出现的错误。

template <class _Pr, class _Ty1, class _Ty2>
constexpr bool _Debug_lt_pred(_Pr&& _Pred, _Ty1&& _Left, _Ty2&& _Right) _NOEXCEPT_COND(
noexcept(_Pred(_Left, _Right))
&& noexcept(_Pred(_Right, _Left))) { // test if _Pred(_Left, _Right) and _Pred is strict weak ordering
const auto _Result = static_cast<bool>(_Pred(_Left, _Right));
if (_Result) {
_STL_VERIFY(!_Pred(_Right, _Left), "invalid comparator");
}

return _Result;
}

我找不到问题。任何帮助都会很棒。

最小可重现示例:

class outlierScore
{
private:
double coreDistance;
public:
double score;
int id;
}
vector <vector<double>> x = {
{0,0.889528896739179,0.536626916823739},
{1,1.30766765703343,0.684794721931497},
{2,0.936505261432846,0.559870334496815}
};
vector<outlierScore> test;
test.push_back(outlierScore(x[0][2], x[0][1], x[0][0]));
test.push_back(outlierScore(x[1][2], x[1][1], x[1][0]));
test.push_back(outlierScore(x[2][2], x[2][1], x[2][0]));

包含看起来像的 outlierScore 对象{id, coreDistance, score}

报错的地方:排序(test.begin(), test.end());

最佳答案

您的实现不正确。

bool outlierScore::operator<(const outlierScore& other) const {
return (score < other.score) ||
(score == other.score && coreDistance < other.coreDistance) ||
(score == other.score && coreDistance == other.coreDistance && id < other.id);
}

或者

bool outlierScore::operator<(const outlierScore& other) const {
return std::tie(score, coreDistance, id) < std::tie(other.score, other.coreDistance, other.id);
}

关于c++ - "invalid comparator": error when overloading the "<" operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56680462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com