返回> 网站首页 

STL 集合操作 交集、差集、并集

yoours2013-06-07 18:27:49 阅读 1531

简介一边听听音乐,一边写写文章。

typedef std::set<string, compare> _SET;

std::ostringstream oss;
    std::streambuf* pOldBuf = std::cout.rdbuf(oss.rdbuf());

_SET s;
s.insert(string("sfdsfd"));
s.insert(string("apple"));
s.insert(string("english"));
s.insert(string("dstd"));
cout<<"s1:"<<endl;

std::set<string, compare>::iterator it = s.begin();
while(it!=s.end())
  cout<<*it++<<"   ";
cout<<endl<<"s2:"<<endl;

_SET s2;
s2.insert(string("abc"));
s2.insert(string("apple"));
s2.insert(string("english"));
it = s2.begin();
while(it!=s2.end())
  cout<<*it++<<"   ";
cout<<endl<<endl;

string str[10];
string *end = set_intersection(s.begin(), s.end(), s2.begin(), s2.end(), str, compare());//求交集,返回值指向str最后一个元素的尾端
cout<<"result of set_intersection s1, s2:"<<endl;
string *first = str;
while(first<end)
cout <<*first++<<" ";
cout<<endl<<endl<<"result of set_union of s1, s2"<<endl;

end = std::set_union(s.begin(), s.end(), s2.begin(), s2.end(), str, compare());//并集
first = str;
while(first<end)
cout <<*first++<<" ";
cout<<endl<<endl<<"result of set_difference of s2 relative to s1"<<endl;

first = str;
end = std::set_difference(s.begin(), s.end(), s2.begin(), s2.end(), str, compare());//s2相对于s1的差集
while(first<end)
cout <<*first++<<" ";
cout<<endl<<endl<<"result of set_difference of s1 relative to s2"<<endl;

first = str;
end = std::set_difference(s2.begin(), s2.end(), s.begin(), s.end(), str, compare());//s1相对于s2的差集
while(first<end)
cout <<*first++<<" ";
cout<<endl<<endl;

first = str;
end = std::set_symmetric_difference(s.begin(), s.end(), s2.begin(), s2.end(), str, compare());//上面两个差集的并集
while(first<end)
cout <<*first++<<" ";
cout<<endl;

std::string ret = oss.str();
std::cout.rdbuf(pOldBuf);//恢复cout的流对象指针
TRACE(ret.c_str());

////////////////////////////////////////////////////////////
set<int> s3;
set<int>::iterator iter = s3.begin();
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(s3, iter));
copy(s3.begin(), s3.end(), ostream_iterator<int>(cout, "   "));// 拷贝到输出流

微信小程序扫码登陆

文章评论

1531人参与,0条评论