是C++ STL里面的set_intersection吗? 如果是很简单,参考下面的代码。 用vector和相应的iterator。 结果保留在vector中,然后把vector转换到数组中(需要保证数组长度足够)。
#include <iostream>#include <algorithm>
#include <vector>
using namespace std
int main(int argc, char** argv)
{
int A[] = {5,10,15,20,25}
int B[] = {50,40,30,20,10}
int C[10] = {0}
size_t size_A, size_B, size_C
vector<int> v
vector<int>::iterator it
// Calculate the size of all arrays.
size_A = sizeof(A)/sizeof(A[0])
size_B = sizeof(B)/sizeof(B[0])
size_C = sizeof(C)/sizeof(C[0])
// Resize vector since it doesn't specify when declaring.
// Sort the vector(s) if applicable.
v.resize(size_A+size_B)
sort (A, A + size_A)
sort (B, B + size_B)
// Get Intersection of 2 sets, and resize it!
it = set_intersection (A, A+size_A, B, B+size_B, v.begin())
v.resize(it-v.begin())
// Print out results.
cout << "The intersection has " << (v.size()) << " elements:" << endl
for (it=v.begin() it!=v.end() 橘谨芦++it)
cout << ' ' << *it
cout << endl
// Now converting vector to array.
if (size_C < v.size())
{
cout << "Array C is too small." << endl
}
else
{
copy(v.begin(), v.end(), C)
cout <<晌族 "The array of C is:" << endl
for (int i = 0 i < v.size() i ++)
圆带 cout << ' ' << C[i]
cout << endl
}
return 0
}
1.返回空集2.空樱核集的.begin()和.end()是相等的
3.你的set_difference(a.begin(),a.end(),b.begin (),b.end (),inserter(c,it))的意思是比较a和b中不同伏颂腔的元素 将a中与b中不同的元素放到c中
a中是1,b中缺衫是2,不同,所以将a放入c 输出c 是1
包括头文件:
#include <algorithm>
#include <set>
集合函数:
set<int> S1,S2
S1.insert(1)//插入一个元素1
S2.insert(2)//插入一个元素2
set<轮旁数int>::iterator site //迭代器,用法同vector
set<int> Si
set<int>vis
set_intersection( S.begin(), S.end(), S2.begin(), S2.end(), inserter( Si, Si.begin() ) ) //Si为求交后的集腊首合
set_union(...)//并,语法同上
set_difference(...) //差,语法同上
vis.clear() 移除set容器内所有元素
vis.count(s) 返回vis中值为s的个数
if(vis.count(s)) 判断s是否在集合vis中
vis.find(s) 返回s所在位置,如找不到,返回end(),即为vis,fing(s)==vis.end() vis.insert(s) 把s加入集合
vis.remove(s) 从集合中移除s
输出:
启基 set<int>::iterator ii
for(ii=si.begin()ii!=si.end()ii++)
cout<<(*ii)<<' '
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)