使用自定义类集时出错

Error using set of custom class

本文关键字:出错 自定义      更新时间:2023-10-16

当我尝试编译以下代码时,我得到

'const elem' is not derived from 'const std::__cxx11::sub_match<_BiIter>'

我不明白这是什么意思,我的代码有什么问题?

struct elem
{
    int x,y,val;
    elem(int x,int y,int val)
    {
        this->x = x;
        this->y = y;
        this->val = val;
    }
    bool operator<(const elem b)
    {
        return val > b.val;
    }
};

int kthSmallest(int v[MAX][MAX], int n, int k)
{
    set<pair<int,int>> m;
    priority_queue<elem, vector<elem>> pq;
    int temp = k;
    pq.emplace(0,0,v[0][0]);
    while(temp != 0)
    {
        temp--;
        if(pq.top().x + 1 < n && m.find(make_pair(pq.top().x + 1, pq.top().y)) == m.end())
        {
            m.insert(make_pair(pq.top().x + 1, pq.top().y));
            pq.emplace(pq.top().x + 1, pq.top().y, v[pq.top().x + 1][pq.top().y]);
        }
        if(pq.top().y + 1 < n && m.find(make_pair(pq.top().x + 1, pq.top().y)) == m.end())
        {
            m.insert(make_pair(pq.top().x, pq.top().y + 1));
            pq.emplace(pq.top().x, pq.top().y + 1, v[pq.top().x][pq.top().y + 1]);
        }
    }
    return pq.top().val;
}

std::priority_queue 的第三个模板参数是 Compare - 二进制运算符,默认情况下为 std::less。它需要两个参数作为const。您的第一个参数 operator<(默认情况下是调用它的对象)不const,因为该方法未const 。这就是为什么您需要按照评论中指出的那样更改它的原因:

bool operator<(const elem b) const
{
    return val > b.val;
}