联合操作对于std :: set [英] Union Operation For std::set

查看:131
本文介绍了联合操作对于std :: set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

还是这样?

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

set_union 是名称中正确的函数。它也可以在向量上操作,这意味着它可能不如 set -only函数有效。 p>

不添加。 附加删除原始集。我想要一个表示联合的集。

解决方案

-iterator 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;
}






/ strong>:下面的一些意见建议我采取一个参数的值,因为我需要一个副本反正我选择这个实现,以避免不允许RVO,这是不允许的,当返回参数的值。为了更好地处理右值参数,可以提供这个函数的重载,取值为偏值引用和利用移动语义。


Is there no function in the standard library like this?

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

Or even this?

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

set_union is the right function in name only. It can operate on vector also, which means it may not be as efficient as a set-only function.

I am not appending. Appending destroys the original set. I want a new set representing the union.

解决方案

You can use the two-iterator std::set::insert template for this:

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


Note: Following some of the comments suggesting I take one of the parameters by value because I need a copy anyway, I chose this implementation to avoid disallowing RVO, which is not allowed when returning parameter taken by value. To better deal with rvalue arguments, overloads of this function taking rvalue reverences and leveraging move semantics could be provided.

这篇关于联合操作对于std :: set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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