如何在C ++中找到两个std :: set的交集? [英] how to find the intersection of two std::set in C++?
问题描述
我一直试图在C ++中找到两个std :: set之间的交集,但我一直遇到错误.
I have been trying to find the intersection between two std::set in C++, but I keep getting an error.
为此我创建了一个小样本测试
I created a small sample test for this
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
int main() {
set<int> s1;
set<int> s2;
s1.insert(1);
s1.insert(2);
s1.insert(3);
s1.insert(4);
s2.insert(1);
s2.insert(6);
s2.insert(3);
s2.insert(0);
set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end());
return 0;
}
后一个程序不会生成任何输出,但是我希望具有以下值的新集(将其称为s3
):
The latter program does not generate any output, but I expect to have a new set (let's call it s3
) with the following values:
s3 = [ 1 , 3 ]
相反,我得到了错误:
test.cpp: In function ‘int main()’:
test.cpp:19: error: no matching function for call to ‘set_intersection(std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>)’
我从此错误中了解到的是,set_intersection
中没有定义接受Rb_tree_const_iterator<int>
作为参数.
What I understand out of this error, is that there's no definition in set_intersection
that accepts Rb_tree_const_iterator<int>
as parameter.
此外,我想std::set.begin()
方法返回此类对象
Furthermore, I suppose the std::set.begin()
method returns an object of such type,
是否有更好的方法在C ++中找到两个std::set
的交集?最好是内置功能?
is there a better way to find the intersection of two std::set
in C++? Preferably a built-in function?
非常感谢!
推荐答案
您尚未为 set_intersection
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_intersection ( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result );
通过类似
...;
set<int> intersect;
set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),
std::inserter(intersect,intersect.begin()));
您需要一个std::insert
迭代器,因为该集合截至目前为空.我们不能使用back_或front_inserter,因为set不支持这些操作.
You need a std::insert
iterator since the set is as of now empty. We cannot use back_ or front_inserter since set doesnt support those operations.
这篇关于如何在C ++中找到两个std :: set的交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!