【问题标题】:Union Operation For std::set [duplicate]std::set 的联合操作 [重复]
【发布时间】:2014-05-02 21:11:31
【问题描述】:

标准库中没有这样的函数吗?

set<T> set::union(set<T> other)

甚至这个?

set<T> getUnion(set<T> a, set<T> b)

set_union 只是名义上的正确函数。它也可以在vector 上运行,这意味着它可能不如set-only 函数高效。

没有追加。 追加会破坏原始集合。我想要一个代表联合的集。

【问题讨论】:

  • @Dlotan 我不想追加。我想要一个代表工会的新集合。
  • @ChrisRedford 查看副本的第二个答案,set_union
  • @ChrisRedford 当你追加时,你会得到一个联合。
  • @DanielFrey 在询问之前我就知道set_union,它只是名义上的正确功能。它也可以对向量进行操作,这意味着它可能不如set-only 函数高效。

标签: c++


【解决方案1】:

您可以为此使用两个迭代器 std::set::insert 模板:

template <typename T>
std::set<T> getUnion(const std::set<T>& a, const std::set<T>& b)
{
  std::set<T> result = a;
  result.insert(b.begin(), b.end());
  return result;
}

注意:根据一些 cmets 建议我按值获取参数之一,因为无论如何我都需要一个副本,我选择了这个实现以避免不允许 RVO,这在返回参数时是不允许的按价值。为了更好地处理右值参数,可以提供此函数的重载,该函数采用右值尊重并利用移动语义。

【讨论】:

  • std::set_union 会不会更有效率?
  • 专业提示:当您将 const 引用传递给函数然后立即获取它的副本时,只需按值传递即可。
  • @MarkRansom 我要退回副本,我不想禁止 RVO。复制参数并返回它会抑制它。所以在这种情况下,我认为专业提示不是一个好的提示。
  • @sehe 我不确定。它在比较中是线性的,但每个集合插入都是 log(N)。还是我错过了什么?
  • @juanchopanza,谢谢你的链接,我也很好奇。只是表明您不能依赖任何经验法则。
【解决方案2】:

std::set_union

该页面中的示例使用向量和数组,因此用途广泛:

// set_union example
#include <iostream>     // std::cout
#include <algorithm>    // std::set_union, std::sort
#include <vector>       // std::vector

int main () {
  int first[] = {5,10,15,20,25};
  int second[] = {50,40,30,20,10};
  std::vector<int> v(10);                      // 0  0  0  0  0  0  0  0  0  0
  std::vector<int>::iterator it;

  std::sort (first,first+5);     //  5 10 15 20 25
  std::sort (second,second+5);   // 10 20 30 40 50

  it=std::set_union (first, first+5, second, second+5, v.begin());
                                               // 5 10 15 20 25 30 40 50  0  0
  v.resize(it-v.begin());                      // 5 10 15 20 25 30 40 50

  std::cout << "The union has " << (v.size()) << " elements:\n";
  for (it=v.begin(); it!=v.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

输出:

联合有8个元素: 5 10 15 20 25 30 40 50

【讨论】:

  • 不过,这对std::set 并不适用。
  • 他要求找到集合的并集,而不是向量...而您的答案直接从cplusplus.com/reference/algorithm/set_union@keyser 复制而来
  • @fardinabir 检查链接;链接到示例的 OP(引用它);所以这不会是抄袭。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 1970-01-01
  • 2016-11-14
  • 2014-03-15
相关资源
最近更新 更多