有两种方法可以对两种不同类型的集合进行std :: set_intersection吗?
Is there any way to do std::set_intersection on two different types of sets?
我有两套:
std::set<X1> l_set1; std::set<X2> l_set2;我能够为他们定义一些比较器,以检查X1和X2是否相等.
I'm able to define some comparator for them that checks if X1 and X2 are equal.
struct sample_comparer { bool operator()(const &X1 p_left, const &X2 p_right) { return p_left == p_right; } };现在,我尝试在这两个集合上做一个集合交集:
Now, I try to do a set intersection on those two sets:
std::set<X1> l_intersect; std::set_intersection(l_set1.begin(), l_set1.end(), l_set2.begin(), l_set2.end(), std::inserter(l_intersect, l_intersect.begin()), sample_comparer());不幸的是,我不能强迫此代码正常工作.我什至不确定这是否可行,但从set_intersection I的描述知道我可以使用两个不同的迭代器.
Unfortunately, I can't force this code to work. I'm not even sure if this is possible, but from the description of set_intersection I know that I can use two different iterators.
我试图搜索一些符合我要求的代码示例,但没有找到?有人可以为我解决我的问题的工作代码示例吗?
I tried to search for some code samples that do what I want, but didn't found any? Could someone present me a working code sample for my problem?
更新: 错误是:
错误:stl_function.h:227:"operator<"不匹配在'__x<中__y'
error: stl_function.h:227: no match for 'operator<' in '__x < __y'
提前谢谢!
推荐答案PlasmaHH的评论可能是问题所在.
The comment by PlasmaHH is likely the problem.
set_intersection之类的功能的工作方式是:首先执行a < b,然后执行b < a
The way functions like set_intersection work is they first do: a < b and then b < a
因此,ample_comparer需要能够比较两种方式:
As a result ample_comparer needs to be able to compare both ways:
struct sample_comparer { bool operator()(const &X1 p_left, const &X2 p_right) { return p_left == p_right; } bool operator()(const &X2 p_left, const &X1 p_right) { return p_left == p_right; } };以下内容实际上并没有做任何明智的事情-但它确实可以干净地编译:
The following doesn't actually do anything sensible - but it does compile cleanly:
struct A { struct Compare { bool operator () (A const &, A const &) { return false;} }; }; struct B { struct Compare { bool operator () (B const &, B const &) { return false; } }; }; typedef std::set<A, A::Compare> S1; typedef std::set<B, B::Compare> S2; class IntersectionCompare { public: bool operator ()(S1::value_type, S2::value_type) { return false; } bool operator ()(S2::value_type, S1::value_type) { return false; } }; void bar (S1 & s1, S2 & s2) { S1 result; std::set_intersection (s1.begin () , s1.end () , s2.begin () , s2.end () , std :: insert_iterator< S1 > (result, result.end ()) , IntersectionCompare ()); }更多推荐
两种不同类型的集合的set
发布评论