C++ vector of priority_queue of strings with custom strings comparator

两盒软妹~` 提交于 2021-01-28 21:18:23

问题


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;
};

回答1:


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.



来源:https://stackoverflow.com/questions/36407607/c-vector-of-priority-queue-of-strings-with-custom-strings-comparator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!