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

原文链接: https://www.cnblogs.com/s1124yy/p/5849553.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    set_union的几个例子

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/240113

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午8:28
下一篇 2023年2月13日 下午8:29

相关推荐