C++ STL 容器的合并、求差集、交集等操作实例
作者:互联网
//本实例程序演示容器之间合并、求差集、求交集
//merge、inplace_merge、set_union、set_difference、set_intersection、
#include <iostream>
#include <list>
#include <set>
#include <algorithm>
#include <iterator>
using namespace std;
//打印容器中的元素
void print(const int& elem){
cout<<elem<<",";
}
int main()
{
int dim[]={1,2,3,4,5,6,7}; //用于初始化l1
int dim2[]={3,4,5}; //用于初始化s1
list<int> l1;
set<int> s1;
for(int i=0;i<sizeof(dim)/sizeof(int);++i){
l1.push_back(dim[i]); //l1初始化
}
for(int i=0;i<sizeof(dim2)/sizeof(int);++i){
s1.insert(dim2[i]); //s1初始化
}
for_each(l1.begin(),l1.end(),print); //显示容器l1
cout<<endl;
for_each(s1.begin(),s1.end(),print); //显示容器s1
cout<<endl<<"merge(合并l1和s1,相同元素不消除):"<<endl;
//l1和s1合并,相同元素叠加机制
merge(l1.begin(),l1.end(),s1.begin(),s1.end(),ostream_iterator<int>(cout,","));
cout<<endl;
cout<<"set_union(合并并消除多余相同元素):"<<endl;
//l1和s1合并并消除多余相同元素
set_union(l1.begin(),l1.end(),s1.begin(),s1.end(),ostream_iterator<int>(cout,","));
cout<<endl;
cout<<"set_difference(求差集):"<<endl;
//求l1和s1的差集
set_difference(l1.begin(),l1.end(),s1.begin(),s1.end(),ostream_iterator<int>(cout,","));
cout<<endl;
cout<<"set_intersection(求交集):"<<endl;
//求l1和s1的交集
set_intersection(l1.begin(),l1.end(),s1.begin(),s1.end(),ostream_iterator<int>(cout,","));
cout<<endl;
return 0;
}
标签:容器,set,cout,STL,求差,C++,int,include 来源: https://www.cnblogs.com/FrostyForest/p/15361050.html