I have the following code:
bool custom(pair<int, int>& a, pair<int, int>& b)
{
return (double)a.first / (double)a.second > (double)b.first / (double)b.second;
}
int reviews(vector<pair<int,int>>& ratings, int t) {
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&custom)> q;
int numProducts = ratings.size();
double rating = 0;
int numRevs = 0;
// fill up queue and compute initial rating
for (int i = 0; i < ratings.size(); i++)
{
rating += ((double)ratings[i].first / (double)ratings[i].second) / numProducts;
q.push(ratings[i]);
}
// other stuff, crashes before this point
return numRevs;
}
int main()
{
vector<pair<int, int>> ratings = { {4,4}, {1,2}, {3,6} };
int t = 80;
cout << reviews(ratings , t) << endl;
}
Which gives the following error the second time q.push() is run: Exception thrown at 0x00000000 in ConsoleApplication1.exe: 0xC0000005: Access violation executing location 0x00000000.
Does anyone know why this is? Thanks
Pass custom
method as q
's parameter. So, change this:
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&custom)> q;
to this:
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&custom)> q(custom);
The reason for that is that in std::priority_queue
, the third template parameter is:
Compare - A Compare type providing a strict weak ordering.
That means that in your code you had only specified the type of the comparator only (decltype(&custom)
), a function pointer. As a result the function object will be default-constructed. Using a default constructed function pointer will invoke undefined behavior. So you need to pass the actual function object, in order for it to be correctly usable.
PS: You might want to take a look in this relevant lambda-using example.
User contributions licensed under CC BY-SA 3.0