Reputation: 2623
I'm trying to understand the syntax for std::set_intersection
when using a custom comparator.
I'm trying to get the intersection of sets one
and two
, which should result in a set (intersect
) containing only element f2
.
I get error:
passing ‘const Foo’ as ‘this’ argument discards qualifiers
#include <set>
#include <string>
struct Foo
{
std::string str;
};
struct Compare_custom
{
bool operator () (const Foo & lhs, const Foo & rhs)
{
return (lhs.str.size() > rhs.str.size());
}
};
int main ()
{
std::set<Foo, Compare_custom> one, two, intersect;
Foo f1, f2, f3;
f1.str = "-";
f2.str = "--";
f3.str = "---";
one.insert(f1);
one.insert(f2);
two.insert(f2);
two.insert(f3);
std::set_intersection(one.begin(), one.end(),
two.begin(), two.end(),
intersect.begin(), Compare_custom());
}
What am I doing wrong?
Upvotes: 2
Views: 795
Reputation: 2226
You are using std::set_intersection
wrongly for std::set
. Try this :
std::set_intersection(one.begin(), one.end(),
two.begin(), two.end(),
std::inserter(intersect, intersect.begin()), Compare_custom());
Upvotes: 3