我在尝试理解使用自定义比较器时 std::set_intersection
的语法。
我正在尝试获取集合 one
和 two
的交集,这将导致集合 (intersect
) 仅包含元素 f2
.
我得到错误:
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());
}
我做错了什么?
最佳答案
您错误地为 std::set
使用了 std::set_intersection
。试试这个:
std::set_intersection(one.begin(), one.end(),
two.begin(), two.end(),
std::inserter(intersect, intersect.begin()), Compare_custom());
关于c++ - 带有自定义比较器的 std::set_intersection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49828583/