如何找到两个std:set在C ++中? [英] how to find the intersection of two std:set in C++?

查看:247
本文介绍了如何找到两个std:set在C ++中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试找到两个std :: set在C ++中的交集,但我一直收到一个错误。

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: (std :: _ Rb_tree_const_iterator< int>,std :: _ Rb_tree_const_iterator< int>,std :: _ Rb_tree_const_iterator< int>,std()':
test.cpp:19:error:没有匹配的函数:: _ 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,

有没有更好的方法来找到两个std :: set在C ++的交集?最好是内置函数?

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 );

通过执行以下操作来修复此问题:

Fix this by doing something like

...;
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.

这篇关于如何找到两个std:set在C ++中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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