1 回答
TA贡献1895条经验 获得超7个赞
#include <set>
#include <iostream>
int main()
{
int a[4] = {2, 3, 454, 67};
int b[4] = {223, 23, 45, 454};
int c[4] = {23, 87, 223, 452};
std::set<int> set(a, a+4);
set.insert(b, b+4);
set.insert(c, c+4);
for (auto i : set)
std::cout << i << " ";
std::cout << std::endl;
return 0;
}
需要C++11 支持。
如果不想用c++11,只需要改一下输出:
for (std::set<int>::iterator iter = set.begin(); iter != set.end(); ++iter)
std::cout << *iter << " ";
std::cout << std::endl;
鉴于题主想用比较底层的方法,类似纯C的方式,即不用STL的函数。那样思路就要分几个步骤了:
合并到一个大数组里去
将大数组排序
去掉大数组中的重复项
我用C语言简单实现了上述步骤,没有考虑算法效率,仅供参考:
#include <stdio.h>
#include <stdlib.h>
int* unique(int* first, int* last)
{
if (first==last) return last;
int* result = first;
while (++first != last)
{
if (!(*result == *first))
*(++result)=*first;
}
return ++result;
}
void merge(int a[], int b[], int beg, int size)
{
for (int i=0; i<size; ++i)
a[beg+i] = b[i];
}
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main()
{
int a[4] = {2, 3, 454, 67};
int b[4] = {223, 23, 45, 454};
int c[4] = {23, 87, 223, 452};
int d[12];
merge(d, a, 0, 4);
merge(d, b, 4, 4);
merge(d, c, 8, 4);
qsort (d, 12, sizeof(int), compare);
int *end = unique(d, d+12);
for (int *p = d; p != end; ++p)
printf("%d ", *p);
return 0;
}
- 1 回答
- 0 关注
- 1005 浏览
添加回答
举报