0

I have to use my operator as a comparator for the two pointer inputs but I am stuck on pushing those actual inputs in the queue as my comparator takes const int as inputs while arrange takes 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;
    }
};
Apples
  • 2,655
  • 17
  • 22
J.Doe
  • 15
  • 1
  • 6
  • Missing a few `*`s there. `const int&` is a reference to an `int`, not an `int *`. You really sure you want to store pointers to `int`s? – user4581301 Apr 16 '19 at 21:58
  • a and b are actually the locations to ints in a vector – J.Doe Apr 16 '19 at 22:16
  • Sounds reasonable, but make sure you are familiar with the [Iterator Invalidation Rules](https://stackoverflow.com/questions/6438086/iterator-invalidation-rules) – user4581301 Apr 17 '19 at 02:58

1 Answers1

1

If a container contains pointers, you have to use pointers throughout.

Marked and explained changes with comments in code.

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);
}
user4581301
  • 29,019
  • 5
  • 26
  • 45