• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ACM s1124yy
守りたいものが 強くさせること
博客园    首页    新随笔    联系   管理     

set_union的几个例子

获得两个集合的并集。两个输入序列须保证已排好序。
数组用的时候

// set_union example  
#include <iostream>  
#include <algorithm>  
#include <vector>  
using namespace std;  
  
int main () {  
  int first[] = {5,10,15,20,25};  
  int second[] = {50,40,30,20,10};  
  vector<int> v(10);                           // 0  0  0  0  0  0  0  0  0  0  
  vector<int>::iterator it;  
  
  sort (first,first+5);     //  5 10 15 20 25  
  sort (second,second+5);   // 10 20 30 40 50  
  
  it=set_union (first, first+5, second, second+5, v.begin());  
                                               // 5 10 15 20 25 30 40 50  0  0  
  cout << "union has " << int(it - v.begin()) << " elements.\n";  
  return 0;  
}  

set用的时候

// set_union2 example  
#include <set>  
#include <iterator>  
#include <iostream>  
#include <algorithm>  
using namespace std;  
  
int main(void)  
{  
    set<int> a,b,c;  
    a.insert(1);  
    a.insert(6);  
    a.insert(6);  
    b.insert(2);  
    b.insert(6);  
    b.insert(9);  
  
    //最后一个参数若使用c.begin()会产生编译错误assignment of read-only localtion.  
  
    set_union(a.begin(), a.end(), b.begin(), b.end(), inserter(c, c.begin()));  
    copy(c.begin(), c.end(), ostream_iterator <int> (cout, " "));  
    return 0;  
}  

vector用的时候

// set_union3 example  
#include <vector>  
#include <iterator>  
#include <iostream>  
#include <algorithm>  
using namespace std;  
  
int main()  
{  
    vector<int> a,b,c;  
    for(int e=0;e<10;e++)  
    {  
       a.push_back(e);  
       b.push_back(e+5);  
    }  
    //最后一个参数若使用c.begin(),运行时会出错“Segmentation fault (core dumped)”.  
    set_union(a.begin(),a.end(),b.begin(),b.end(),back_inserter(c));  
    copy(c.begin(), c.end(), ostream_iterator<int> (cout, " "));  
    return 0;  
}  
posted @ 2016-09-07 15:07  s1124yy  阅读(1349)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3