c++ - 如何使用将 const int 作为 int* 优先级队列的比较器的运算符

标签 c++

我必须使用我的运算符作为两个指针输入的比较器,但我坚持将这些实际输入插入队列,因为我的比较器将 const int 作为输入,而 arrange 将 int*.

void arrange(int* a, int* b) {
    std::priority_queue<int*, std::vector<int>, compr> q;
    q.push(a);
    q.push(b);
}

struct compr {
    bool operator()(const int& lhs, const int& rhs) const {
        if (lhs%2==0 && rhs%2==0) {
            return lhs>rhs;
        }
        return false;
    }
};

最佳答案

如果容器包含指针,则必须始终使用指针。

在代码中用注释标记和解释更改。

struct compr
{
    bool operator()(int*& lhs, int*& rhs) const 
    //                 ^          ^
    // comparing pointers to ints, not ints
    // also removed cost from the parameters. I'm not sure why, but they 
    // can't be const. Probably an interesting reason behind that, but I 
    // don't know it
    {
        if (*lhs % 2 == 0 && *rhs % 2 == 0) 
        //  ^                ^
            // added dereferences because pointers 
        {
            return *lhs > *rhs; 
            //     ^      ^
            // added dereferences
        }
        return false;
    }
};

void arrange(int* a, int* b)
{
    std::priority_queue<int*, std::vector<int*>, compr> q;
    //                                       ^
    // if the priority queue contains pointers to int, the underlying 
    // container needs to be pointer to int. 
    q.push(a);
    q.push(b);
}

关于c++ - 如何使用将 const int 作为 int* 优先级队列的比较器的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55717106/

相关文章:

C++:如何创建仿函数

c++ - 引用,地址,取消引用和指针的含义

c++ - size_t 到 unsigned int(来自 API 函数)

c++ - 在 Windows 上编译 mongo db 客户端示例时出现链接器错误

c++ - 如何判断 stderr 是否将输出定向到文件?

c++ - 模板类中运算符 [] 的可变模板重载

c++ - 为什么C++全局变量不影响程序的内存使用

c++ - 如何在Qt5 C++中使用QMediaRecorder从QImage序列生成视频文件

C++ typedef typename 类名::模板

c++ - 我可以在不使它变得更复杂的情况下使这个 C++ 代码更快吗?