Compare function on sets

Hello,

How can I declare a set of strings that i want to be ordered by a boolean function Comp? Like the one you would write in
 
sort(v.begin(), v.end(), comp);


I tried
set<string, Comp> S;
but it doesn't work

And the same question for priority queues, can you specify the function you want your elements to be sorted by?

Thanks!!
I tried
set<string, Comp> S;
but it doesn't work
What exactly does not work? Compile time error? Strange runtime behavior?

Comparator should satisfy some requirements. Mainly it should establish strict weak ordering of its operand.

And the same question for priority queues, can you specify the function you want your elements to be sorted by?
Yes. Third template parameter:
1
2
3
4
5
template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;


EDIT: is Comp a class or function?
Last edited on
Unfortunately I think you have to use a functor (a class that defines operator()) instead of a function.

1
2
3
4
5
6
7
struct Comp
{
	bool operator()(const std::string& str1, const std::string& str2)
	{
		return str1 < str2;
	}
};
What I meant by it doesn't work is that it gives a compilation error.
Most people here lacking mind reading abilities, so text of that error would be helpful.

If comp is a function, then your declarationis invalid. Second template parameter should be type, not the function name.
You need to either use Functors as Peter87 suggested, or use function wrapper:
1
2
3
4
5
6
7
8
9
10
11
#include <functional>

bool compare(int x, int y)
{
    return x > y;
}

int main()
{
    std::set<int, std::function<bool(int, int)>> x(compare);
}


Edit: tecknically you can use function pointers too: set<string, bool (*)(string, string)>
Last edited on
Topic archived. No new replies allowed.