0

Running the following example I receive a debug assertion in the marked line.

std::priority_queue<int, std::vector<int>, std::greater_equal<int>> queue_int;
queue_int.push(1);
queue_int.push(2);
queue_int.push(1); // Debug Assertion Failed: Expression invalid comparator

Any hints? Help much appreciated!

3 Answers 3

4

All the time when you are using a STL data structure with a comparator, that comparator needs to be strict and never return true if it is receiving equal object to compare.

Imagine the case when 2 equal objects are compared, swapped and the next comparation will be again between the same 2 objects. In this case the STL sort step will never stop.

Try std::greater instead of std::greater_equal

Sign up to request clarification or add additional context in comments.

2 Comments

I understood your explanation but I'm still wondering about std::greater_equal? Could you come up with an example on when to use it...
I don't think that std::greater_equal is ever used for STL data structures (but maybe I am wrong). Almost all the time you will find in STL more functions than you strictly need, because somebody could use them in personal tasks. Tasks like: count the elements in an array >= 0 (find the example here: cplusplus.com/reference/functional/greater_equal )
1

You have undefined behaviour. Your implementation is nice, and asserts when it detects that. The comparator used with std::priority_queue must meet the named requirement Compare. std::greater_equal does not, because it returns true if you pass it equal values.

From the relevant documentation

The type T satisfies Compare if

Given

  • comp, an object of type T

Requirements

  • For all a, comp(a,a)==false

1 Comment

Thanks for your help!
-2

Can not reproduce with:

#include <stdio.h>
#include <vector>
#include <queue>

int main(int argc, char **argv)
{
    std::priority_queue<int, std::vector<int>, std::greater_equal<int>> queue_int;
    queue_int.push(1);
    queue_int.push(2);
    queue_int.push(1); // Debug Assertion Failed: Expression invalid comparator
    return 0;
}

And compilation line:

$ g++ -std=c++17 -o main main.cpp

Please specify exact compilation flags used

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.