Compare function on sets

Oct 18, 2014 at 10:13am
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!!
Oct 18, 2014 at 10:50am
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 Oct 18, 2014 at 10:52am
Oct 18, 2014 at 10:57am
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;
	}
};
Oct 18, 2014 at 10:59am
What I meant by it doesn't work is that it gives a compilation error.
Oct 18, 2014 at 11:04am
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 Oct 18, 2014 at 11:06am
Topic archived. No new replies allowed.