1

I have a vector of priority_queues of strings:

vector<priority_queue<string>>> queues(VECTOR_CAPACITY);

And the question is how can I apply custom string comparator to those priority_queues?

Should this be relevant, the comparator I want puts shorter strings before longer ones and when they're equal length uses standard strings comparison.

I tried this way:

auto comparator = [] (string s1, string s2) { return s1.length() < s2.length() || s1 < s2; };
vector<priority_queue<string, vector<string>, decltype(comparator)>> queues(VECTOR_CAPACITY);

but it doesn't compile with the following error:

No matching constructor for initialization of 'value_compare' (aka
'(lambda at Example.cpp:202:23)')

EDIT: Comparator that puts shorter strings before longer ones and when they're equal length uses standard lexicographic comparison looks like that:

auto comparator = [] (string s1, string s2)
{
    if (s1.length() != s2.length())
    {
        return s1.length() > s2.length();
    }
    return s1.compare(s2) > 0;
};
kostek
  • 801
  • 2
  • 15
  • 32
  • A suggested answer for your **how can I apply a custom** `string` **comparator?** question: One idea that I can think of is to make a custom class that has a `string` as it's only member. With this you could overload the comparator operators to first check the length of the two strings, and if they're equal, then use the `string`'s comparator's themselves to determine which is greater than the other. This is just a suggestion, there may be better ways of doing this. I believe that this is what you are asking for, is it not? – Fearnbuster Apr 04 '16 at 16:19

1 Answers1

4

You also need to pass the instance of your lambda to the std::priority_queue, as this Q&A says:

using my_queue_t = std::priority_queue<
    std::string, std::vector<std::string>, decltype(comparator)>;

std::vector<myqueue_t> queues(VECTOR_SIZE, my_queue_t(comparator));

Unfortunately, copy-list-initialization i.e. {comparator} doesn't work here, because the 2nd constructor overload is marked explicit for some reason.


I changed VECTOR_CAPACITY to VECTOR_SIZE because that's what the parameter means.

Community
  • 1
  • 1
LogicStuff
  • 19,397
  • 6
  • 54
  • 74