如何找到两个STL集合的交集?

124

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

为此,我创建了一个小的样本测试。

#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)具有以下值:

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>作为参数的定义。

此外,我认为std::set.begin()方法返回一个这种类型的对象,

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


"我期望有一个新的集合(我们称之为s3),但你没有得到它,也没有实现。我不明白你期望结果去哪里了。另外,你没有阅读文档以查找要传递的参数是什么。" - Lightness Races in Orbit
6个回答

153

你没有为 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迭代器。我们不能使用std::back_inserterstd::front_inserter,因为集合不支持这些操作。


120
我希望了解为什么对集合的这种基本操作需要如此繁琐晦涩的咒语。为什么不使用一个简单的set<T>& set::isect(set<T>&)方法来完成所需的操作呢?(我想要一个set<T>& set::operator^(set<T>&),但那可能太过分了。) - Cognitive Hazard
3
@RyanV.Bissell,这个算法与 <algorithm> 中的大多数算法设计相似,因此具有一致性。我认为这种风格还可以提供灵活性,并允许算法与多个容器一起使用,尽管在这里可能不会发生。此外,你的签名可能无法工作,你可能需要返回一个值。在没有复制语义的日子里,这将是一个双重复制。(这句话意思不太明确)我已经有一段时间没有使用C++了,所以接受这些信息时请保留一些怀疑。 - Karthik T
6
我仍然认为自己是STL的新手,因此也适用于盐粒(指微小细节)。我的评论编辑窗口已过期,因此我无法更正返回引用的错误。我的评论并不是在抱怨一致性,而是一个诚实的问题,为什么这个语法必须如此难懂。也许我应该将其作为一个SO问题提出来。 - Cognitive Hazard
5
实际上,大部分的C++标准库都是以这种晦涩难懂的方式设计的。虽然设计的优雅之处显而易见(尤其是对于通用性方面的考量),但是API的复杂性带来了毁灭性的影响(主要是因为人们一直在重新发明轮子,因为他们无法使用编译器提供的那些)。在另一个世界,设计者们会因为偏爱自己的乐趣而被批评。但在这个世界里...好在我们至少有StackOverflow。 - user948581
3
这是一个“通用语法”-您也可以在向量和列表上执行set_intersection,将结果存储到deque中,并且您应该能够有效地执行此操作(当然,在调用它之前,确保两个源容器都已排序)。我觉得这不错,唯一让我有问题的是,可能还有一种使用另一个set进行交集操作的方法。传递容器而不是“.begin()”-“.end()”是另一回事-一旦C++拥有概念,这将得到解决。 - Ethouris
显示剩余9条评论

27

8
back_inserter 不能与 set 一起使用,因为 set 没有 push_back 函数。 - Jack Aidley

10

被接受的答案中第一个(得票较高)评论抱怨现有std集合操作缺少运算符。

一方面,我理解标准库中缺少这些运算符。另一方面,如果需要,很容易添加它们(为了个人的快乐)。 我重载了

  • operator *() 用于交集
  • operator +() 用于并集。

示例 test-set-ops.cc:

#include <algorithm>
#include <iterator>
#include <set>

template <class T, class CMP = std::less<T>, class ALLOC = std::allocator<T> >
std::set<T, CMP, ALLOC> operator * (
  const std::set<T, CMP, ALLOC> &s1, const std::set<T, CMP, ALLOC> &s2)
{
  std::set<T, CMP, ALLOC> s;
  std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
    std::inserter(s, s.begin()));
  return s;
}

template <class T, class CMP = std::less<T>, class ALLOC = std::allocator<T> >
std::set<T, CMP, ALLOC> operator + (
  const std::set<T, CMP, ALLOC> &s1, const std::set<T, CMP, ALLOC> &s2)
{
  std::set<T, CMP, ALLOC> s;
  std::set_union(s1.begin(), s1.end(), s2.begin(), s2.end(),
    std::inserter(s, s.begin()));
  return s;
}

// sample code to check them out:

#include <iostream>

using namespace std;

template <class T>
ostream& operator << (ostream &out, const set<T> &values)
{
  const char *sep = " ";
  for (const T &value : values) {
    out << sep << value; sep = ", ";
  }
  return out;
}

int main()
{
  set<int> s1 { 1, 2, 3, 4 };
  cout << "s1: {" << s1 << " }" << endl;
  set<int> s2 { 0, 1, 3, 6 };
  cout << "s2: {" << s2 << " }" << endl;
  cout << "I: {" << s1 * s2 << " }" << endl;
  cout << "U: {" << s1 + s2 << " }" << endl;
  return 0;
}

已编译并测试:

$ g++ -std=c++11 -o test-set-ops test-set-ops.cc 

$ ./test-set-ops     
s1: { 1, 2, 3, 4 }
s2: { 0, 1, 3, 6 }
I: { 1, 3 }
U: { 0, 1, 2, 3, 4, 6 }

$ 

我不喜欢运算符中返回值的复制。也许可以使用移动赋值来解决,但这仍然超出了我的能力范围。
由于我对这些“新奇”的移动语义知识有限,我担心运算符返回可能会导致返回集合的副本。Olaf Dietsche指出这种担忧是不必要的,因为std::set已经配备了移动构造/赋值。
尽管我相信他,但我在考虑如何检查这一点(类似于"自我说服")。实际上,这很容易。由于模板必须在源代码中提供,因此您可以使用调试器逐步进行排查。因此,我在operator *()return s;处设置了断点,并进行了单步操作,立即进入了std::set::set(_myt&& _Right):et voilà——移动构造函数。感谢Olaf给我的启示。
为了完整起见,我也实现了相应的赋值运算符。
  • operator *=() 用于集合的“破坏性”交集
  • operator +=() 用于集合的“破坏性”并集。

示例test-set-assign-ops.cc:

#include <iterator>
#include <set>

template <class T, class CMP = std::less<T>, class ALLOC = std::allocator<T> >
std::set<T, CMP, ALLOC>& operator *= (
  std::set<T, CMP, ALLOC> &s1, const std::set<T, CMP, ALLOC> &s2)
{
  auto iter1 = s1.begin();
  for (auto iter2 = s2.begin(); iter1 != s1.end() && iter2 != s2.end();) {
    if (*iter1 < *iter2) iter1 = s1.erase(iter1);
    else {
      if (!(*iter2 < *iter1)) ++iter1;
      ++iter2;
    }
  }
  while (iter1 != s1.end()) iter1 = s1.erase(iter1);
  return s1;
}

template <class T, class CMP = std::less<T>, class ALLOC = std::allocator<T> >
std::set<T, CMP, ALLOC>& operator += (
  std::set<T, CMP, ALLOC> &s1, const std::set<T, CMP, ALLOC> &s2)
{
  s1.insert(s2.begin(), s2.end());
  return s1;
}

// sample code to check them out:

#include <iostream>

using namespace std;

template <class T>
ostream& operator << (ostream &out, const set<T> &values)
{
  const char *sep = " ";
  for (const T &value : values) {
    out << sep << value; sep = ", ";
  }
  return out;
}

int main()
{
  set<int> s1 { 1, 2, 3, 4 };
  cout << "s1: {" << s1 << " }" << endl;
  set<int> s2 { 0, 1, 3, 6 };
  cout << "s2: {" << s2 << " }" << endl;
  set<int> s1I = s1;
  s1I *= s2;
  cout << "s1I: {" << s1I << " }" << endl;
  set<int> s2I = s2;
  s2I *= s1;
  cout << "s2I: {" << s2I << " }" << endl;
  set<int> s1U = s1;
  s1U += s2;
  cout << "s1U: {" << s1U << " }" << endl;
  set<int> s2U = s2;
  s2U += s1;
  cout << "s2U: {" << s2U << " }" << endl;
  return 0;
}

编译并测试:

$ g++ -std=c++11 -o test-set-assign-ops test-set-assign-ops.cc 

$ ./test-set-assign-ops
s1: { 1, 2, 3, 4 }
s2: { 0, 1, 3, 6 }
s1I: { 1, 3 }
s2I: { 1, 3 }
s1U: { 0, 1, 2, 3, 4, 6 }
s2U: { 0, 1, 2, 3, 4, 6 }

$

2
std::set 已经实现了必要的移动构造函数和赋值运算符,所以不需要担心这个问题。此外,编译器很可能会使用返回值优化 - Olaf Dietsche
@OlafDietsche 感谢您的评论。我已经检查过并相应地改进了答案。关于RVO,我已经与同事进行了一些讨论,直到我在VS2013的调试器中向他们展示它不会发生(至少在我们的开发平台上)。实际上,这并不重要,除非代码对性能至关重要。在后一种情况下,我现在仍然不依赖RVO。(在C++中这实际上并不难...) - Scheff's Cat
@Scheff,很好的解释。(不是Bose) - JeJo
即使现在,VS对C++17的保证省略支持仍然不足。 - Lightness Races in Orbit

8
请参阅std::set_intersection。你需要加入一个输出迭代器来存储结果:
#include <iterator>
std::vector<int> s3;
set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(), std::back_inserter(s3));

请查看Ideone获取完整清单。

4
请注意,如果您想要的结果也是一个集合,那么back_inserter将无法工作,此时您需要使用类似于Karthik所用的std :: inserter。 - Joseph Garvin

4

在这里评论一下。我认为现在是将联合和交集操作添加到集合接口中的时候了。让我们在未来的标准中提出这个建议。我已经使用了很长时间的std,每次使用集合操作时都希望std更好。对于一些复杂的集合操作,比如交集,您可以简单地(更容易?)修改以下代码:

template <class InputIterator1, class InputIterator2, class OutputIterator>
  OutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1,
                                   InputIterator2 first2, InputIterator2 last2,
                                   OutputIterator result)
{
  while (first1!=last1 && first2!=last2)
  {
    if (*first1<*first2) ++first1;
    else if (*first2<*first1) ++first2;
    else {
      *result = *first1;
      ++result; ++first1; ++first2;
    }
  }
  return result;
}

http://www.cplusplus.com/reference/algorithm/set_intersection/复制:

例如,如果您的输出是一个集合,可以使用output.insert(*first1)。此外,您的函数可能不需要模板化。如果您的代码比使用std set_intersection函数更短,则可以继续使用它。

如果要对两个集合执行联合操作,则可以简单地使用setA.insert(setB.begin(), setB.end())。这比set_union方法简单得多。但是,这在向量中不起作用。


注意:此实现仅适用于已排序的 std::set,而不适用于 std::unordered_set - Sebastian

1
为了保持界面简洁,您可以复制/粘贴此模板:
template<typename Type>
auto setIntersection(set<Type> set0, set<Type> set1)
{
    set<Type> intersection;
    for (auto value : set0)
        if (set1.find(value) != set1.end())
            intersection.insert(value);
    return intersection; 
}

那么在你的情况下

intersection = setIntersection<int>(s1, s2); 

或者

intersection = setIntersection(s1, s2); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接