去除数组中所有重复元素

来源:互联网 发布:bf风森系部落卫衣淘宝 编辑:程序博客网 时间:2024/06/08 18:35

去除数组中所有重复元素,使数组中元素都只有一个,以int为例:

方法有点傻,但是可以实现,有时间再改。

#include <iostream>
#define  ARRAYLEN 13 //数组长度
#define   null -1   // 重复的元素设为-1
using std::cin;
using std::cout;
using std::endl;
int main()
{
int n=ARRAYLEN;
int ncount=0;//重复元素的个数
int Arry[ARRAYLEN]={1,1,2,2,3,5,5,6,7,7,9,8,4};
for (int i=0;i<n;i++)
{
int temp=Arry[i];


for (int j=i;j<n;j++)
{
if (temp==Arry[j+1])
{
Arry[j+1]=null; // 重复的元素设为-1,标识该元素被删除
if (temp!=null)
{
ncount++;//重复元素个数加1
}
}
}
}

//删除标识-1,元素前移
for (int i=0;i<n;i++)
{
int temp=Arry[i];
if (temp==null)
{
for (int k=i;k<n;k++)
{
Arry[k]=Arry[k+1];//前移
}
}
}

for (int i=0;i<n-ncount;i++)
{

cout<<Arry[i]<<endl;
}

return 0;
}

0 0
原创粉丝点击