STL设置差异和交集 [英] STL-set difference and intersection

查看:83
本文介绍了STL设置差异和交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算两个集合的差和相交?
有函数set_differenceset_intersection,它们需要两对源集合的迭代器和结果集合的输出迭代器.在这里,set可以是具有增量迭代器的任何排序容器.还有另一个要求,即输出必须足够大以包含目标范围.
对于STL集,您不能设置它的大小,并且使用空集作为输出会导致断言.实际上,目标空集的输出迭代器等于end(),并且递增迭代器不会将元素添加到集合中.
那么如何计算该值呢?

How to compute difference and intersection of two sets?
There are functions set_difference and set_intersection which requires two pairs of iterators of source sets and output iterator of resulting set. Here, set can be any sorted container with incrementable iterator. There is another requirement that the output should be large enough to contain the destination range.
For STL-set, however, you cannot set the size of it and using an empty set as output leads to assertion. In fact, output iterator of destination empty set is equal to end() and incrementing iterator does not add elements to a set.
So how to compute this?

推荐答案

使用 std :: inserter [std::back_inserter [
Use std::inserter[^] or std::back_inserter[^] for the output iterator. That causes the items to be inserted into the container without having to know what size it should be before you''ve constructed it.

If you''re using a vector or list as the output, I''d use std::back_inserter. For a set, std::inserter is required. Here''s an example:

#include <span class="code-keyword"><vector></span><br />#include <span class="code-keyword"><set></span><br />#include <span class="code-keyword"><iostream></span><br />#include <span class="code-keyword"><algorithm></span><br />#include <span class="code-keyword"><iterator></span><br /><br />int main()<br />{<br />   std::set<int> a, b, c;<br />   a.insert(1);<br />   a.insert(2);<br />   a.insert(3);<br />   a.insert(4);<br />   b.insert(2);<br />   b.insert(4);<br />   b.insert(5);<br />   b.insert(7);<br />   std::vector<int> d;<br /><br />   std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(c, c.end()));<br />   std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(d));<br />   <br />   std::copy(c.begin(), c.end(), std::ostream_iterator<int>(std::cout, " "));<br />   std::copy(d.begin(), d.end(), std::ostream_iterator<int>(std::cout, " "));<br />}






这篇关于STL设置差异和交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆