C++数组间合并

如何实现C++数组间的合并,存在重复项

描述如下:

比如 a[4] = {2, 3, 454, 67}; b[4] = {223, 23, 45, 454}; c[4] = {23, 87, 223, 452};
合并成merge[num] = {2, 3, 23, 45, 67, 87, 223, 452, 454}; num为9; num的值在合并过程中自动累加统计实现!
怎么把数组合并,各数组复的元素重仅仅保留一个!


Cats萌萌
浏览 1017回答 1
1回答

人到中年有点甜

#include <set>#include <iostream>int main(){&nbsp; &nbsp; int a[4] = {2, 3, 454, 67};&nbsp;&nbsp; &nbsp; int b[4] = {223, 23, 45, 454};&nbsp;&nbsp; &nbsp; int c[4] = {23, 87, 223, 452};&nbsp; &nbsp; std::set<int> set(a, a+4);&nbsp; &nbsp; set.insert(b, b+4);&nbsp; &nbsp; set.insert(c, c+4);&nbsp; &nbsp; for (auto i : set)&nbsp; &nbsp; &nbsp; &nbsp; std::cout << i << " ";&nbsp; &nbsp; std::cout << std::endl;&nbsp;&nbsp; &nbsp; return 0;}&nbsp;需要C++11 支持。如果不想用c++11,只需要改一下输出:for (std::set<int>::iterator iter = set.begin(); iter != set.end(); ++iter)&nbsp; &nbsp; std::cout << *iter << " ";std::cout << std::endl;&nbsp;鉴于题主想用比较底层的方法,类似纯C的方式,即不用STL的函数。那样思路就要分几个步骤了:合并到一个大数组里去将大数组排序去掉大数组中的重复项我用C语言简单实现了上述步骤,没有考虑算法效率,仅供参考:#include <stdio.h>#include <stdlib.h>int* unique(int* first, int* last){&nbsp; &nbsp; if (first==last) return last;&nbsp; &nbsp; int* result = first;&nbsp; &nbsp; while (++first != last)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!(*result == *first))&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; *(++result)=*first;&nbsp; &nbsp; }&nbsp; &nbsp; return ++result;}void merge(int a[], int b[], int beg, int size){&nbsp; &nbsp; for (int i=0; i<size; ++i)&nbsp; &nbsp; &nbsp; &nbsp; a[beg+i] = b[i];}int compare (const void * a, const void * b){&nbsp; &nbsp; return ( *(int*)a - *(int*)b );}int main(){&nbsp; &nbsp; int a[4] = {2, 3, 454, 67};&nbsp;&nbsp; &nbsp; int b[4] = {223, 23, 45, 454};&nbsp;&nbsp; &nbsp; int c[4] = {23, 87, 223, 452};&nbsp; &nbsp; int d[12];&nbsp; &nbsp; merge(d, a, 0, 4);&nbsp; &nbsp; merge(d, b, 4, 4);&nbsp; &nbsp; merge(d, c, 8, 4);&nbsp; &nbsp; qsort (d, 12, sizeof(int), compare);&nbsp; &nbsp; int *end = unique(d, d+12);&nbsp; &nbsp; for (int *p = d; p != end; ++p)&nbsp; &nbsp; &nbsp; &nbsp; printf("%d ", *p);&nbsp; &nbsp; return 0;}&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP