簡體   English   中英

重載 c++ 中的小於運算符以用於 std::sort

[英]Overloading less than operator in c++ for use in std::sort

我有一個這樣定義的結構:

struct IFSFunc {
    int a;

    bool operator<(const IFSFunc& other) {
        return a < other.a;
    }
};

由於IFSfunc是一個structoperator<的訪問修飾符應該是public

我也有這個代碼:

#include <algorithm>
std::vector<std::pair<double, IFSFunc>> ifsFuncs;

// fill the vector with various data

std::sort(ifsFuncs.begin(), ifsFuncs.end());

我需要根據配對中的第一個double精度對 ifsFuncs 進行排序。 如果double精度相同,我不關心IFSFunc結構。

但是,要使 std::sort 起作用,其定義如下:

template <class _Ty1, class _Ty2>
_NODISCARD constexpr bool operator<(const pair<_Ty1, _Ty2>& _Left, const pair<_Ty1, _Ty2>& _Right) {
    return _Left.first < _Right.first || (!(_Right.first < _Left.first) && _Left.second < _Right.second);
}

在這種情況下,我必須覆蓋second個小於運算符IFSfunc ,我這樣做了。 但是,嘗試編譯此代碼會給我以下錯誤:

Error C2678 binary '<': no operator found which takes a left-hand operand of type 'const _Ty2' (or there is no acceptable conversion)

為什么?

您需要將該運算符定義為 const 成員 function。

此外,不要只返回 true 進行比較。 這可能導致無限循環。

我只是想通了。 重載的 function 簽名是錯誤的,這就是我需要的:

struct IFSFunc {
    int a;

    bool operator<(const IFSFunc& other) const {
        return a < other.a;
    }
};

請注意, operator<現在是 const function。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM