去年的一道面试题,想起来了,顺遍把代码贴到这里
两个数组合并到一起,然后排序;用set确实比较方面了
#include<iostream>
#include<set>
#include<iterator>
#include<algorithm>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int a[5]={2,5,1,2,3 };
int b[10]={8,9,5,9,7,1,3,4,4,6};
set<int>ist(a,a+sizeof(a)/sizeof(a[0]));
set<int>::iterator itor;
set<int>it(b,b+sizeof(b)/sizeof(b[0]));
set<int>::iterator p;
for( itor = ist.begin();itor !=ist.end();++itor)
{
cout<<*itor<<endl;
}
for(p=it.begin();p!=it.end();++p)
{
cout<<*p<<endl;
}
cout<<"合并后:"<<endl;
set<int>su;
set<int>::iterator q;
set_union(ist.begin(),ist.end(),it.begin(),it.end(),inserter(su,su.begin()));
for(q=su.begin();q!=su.end();++q)
{
cout<<*q<<endl;
}
return 0;
}
}
文章来源:
http://www.blogjava.net/babymouse/archive/2008/08/08/220927.html