0

我正在尝试从 HackerRank 解决这个问题,其中我重载了小于(<) 和小于等于(<=) 运算符,以根据一些自定义条件比较对象。我的代码如下:

#include <bits/stdc++.h>
using namespace std;

class Expenditure
{
public:
    int value;
    int seq;

    Expenditure(int v, int s)
    {
        value = v;
        seq = s;
    }

    bool operator < (const Expenditure &other) const
    {
        if(this->value == other.value)
        {
            return this->seq < other.seq;
        }

        return this->value < other.value;
    }

    bool operator <= (const Expenditure &other) const
    {
        if(this->value == other.value)
        {
            return this->seq <= other.seq;
        }

        return this->value <= other.value;
    }
};

int main()
{
    int n, k, num, notice_count = 0;
    float median_value;
    cin>>n>>k;

    set<Expenditure>window;
    vector<int>arr;

    Expenditure median(-1, -1);

    for(int i = 0; i < n; i++)
    {
        cin>>num;
        arr.push_back(num);

        Expenditure newEntry(num, i);
        window.insert(newEntry);

        if(i == 0)
        {
            median = newEntry;
            median_value = median.value;
        }

        // Insert all the elements of the window first and calculate the median
        if(i < k)
        {
            if((window.size() % 2 == 0) && newEntry < median)
            {
                median = *(--window.lower_bound(median));
            } else if(window.size() % 2 != 0 && median < newEntry)
            {
                median = *(window.upper_bound(median));
            }
        } else
        {
            if(newEntry.value >= 2.0 * median_value)
            {
                notice_count++;
            }

            Expenditure removed(arr[k-i], k-i);
            window.erase(removed);

            // Update the median
            if(median < newEntry && removed <= median)
            {
                median = *(window.upper_bound(median));
            } else if(newEntry < median && median <= removed)
            {
                median = *(--window.lower_bound(median));
            }
        }

        // Update the median value based on window size even or odd
        if(i >= k - 1)
        {
            if(window.size() % 2 == 0)
            {
                median_value = (median.value + (*(window.upper_bound(median))).value)/2.0;
            } else
            {
                median_value = median.value;
            }
        }
    }

    cout<<notice_count<<endl;
}

我遇到分段错误,但在我的本地计算机上,它工作正常。然后,我搜索并看到这可能是由于违反严格的弱排序而发生的。我有两个运算符重载,无法理解这种违规行为。

谁能详细解释我,以及如何避免它并仍然使用重载运算符?

4

0 回答 0