Re: Using Comparator in Set
Quote:
Originally Posted by
Rajesh1978
My doubt is why we can only use functor and not predicate function.
because in algorithms we can use both functor and predicate.
help me understanding it..
"comp" is a type. "cmp" is a function, and functions are values. That's the difference.
That second template argument for set is asking for a type, not a value.
Here is a simple example of this:
Code:
#include <iostream>
#include<set>
using namespace std;
class Test
{
public:
int val;
};
class comp
{
bool operator()(Test a, Test b)
{
return a.val < b.val;
}
};
bool cmp(Test a, Test b)
{
return a.val<b.val;
}
int main()
{
cout << &cmp; // compiles
cout << ∁ // does not compile
}
I can take the address of cmp, but not comp since comp is not a value.
Code:
int main()
{
comp MyComp;
set<Test, MyComp> s; // now this doesn't compile
}
Now the code that uses comp doesn't compile for the same reason. MyComp is now a value (object instance) and not a type, therefore it can't be used as a second parameter to the set functor. The last example is essentially what you're trying to do with the simple function example.
To solve your problem:
Code:
typedef bool (*fn)(Test, Test);
int main()
{
set<Test, fn> s(cmp);
return 0;
}
I defined a function type that takes two Test parameters and returns a bool. Then in the template's second parameter I give the type, and the set constructor I give the actual function to use.
Regards,
Paul McKenzie
Re: Using Comparator in Set
Thanks.
I got it now.
while testing this i got one more confusion.
if i make the comp as below
Code:
class comp
{
bool operator()(Test &a, Test &b) // Added reference to Test
{
return a.val < b.val;
}
};
and try to compile it is giving me a lot of errors
My full code
Code:
#include<iostream>
#include<set>
using namespace std;
class Test
{
public:
Test(int v):val(v){}
int val;
};
class comp
{
public:
bool operator()(Test &a, Test &b)
{
return a.val < b.val;
}
};
bool cmp(Test a, Test b)
{
return a.val<b.val;
}
int main()
{
set<Test,comp>s;
Test t1(10),t2(11),t3(9),t4(-11);
s.insert(t1);
s.insert(t2);
s.insert(t3);
s.insert(t4);
return 0;
}
what difference it makes if i use the reference in the bracket operator overloading.
as I am passing an object I wanted to use the reference.
Is reference not permitted while overloading the '()' operator.
Re: Using Comparator in Set
The parameters should be const reference, not non-const reference.
Re: Using Comparator in Set