两种不同类型的集合的set

编程入门 行业动态 更新时间:2024-10-18 14:14:12
本文介绍了两种不同类型的集合的set_intersection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有两种方法可以对两种不同类型的集合进行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

本文发布于:2023-11-29 03:56:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645195.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两种   不同类型   set

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!