int數組去重,稍微修改,也可以去重其他類型的數組。C++也有庫函數直接調用可去重文章鏈接https://blog.csdn.net/qq_41139830/article/details/80631988
#include "stdafx.h"
#include "windows.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int arr[]={1,2,3,1,2,3,4,1,2,3,1,2,3,1,23,1,2,3};//定義一個int數組並初始化
int len=sizeof(arr)/sizeof(int);//計算數組長度
int * flag=new int[len]();//動態創建標誌數組,和原數組長度一致 加“()”默認每個元素始化爲0,不加表示不初始化
//int * flag=new int[len];//不加()表示不初始化
//for (int i = 0; i < len; i++)
//{
// //cout<<flag[i]<<" ";//輸出標誌原始值
//}
int count=0;//不重複元素計數器
int base=0;//比較基數,每個基數
int times=0;//循環運行次數
for (int i = 0; i < len; i++)
{
if(flag[i]==1)
{
continue;//第i個元素在前面出現過,已經判斷過了,直接跳過,如果不跳過,就重複判斷了
}
base=arr[i];//第i個元素作爲基數,將其和它後面的元素比較,看是否相等
for (int j = i+1; j < len; j++)
{
if(base==arr[j]&&flag[j]==0)//判斷基數和其後面元素是否相等,並且沒出現過
{
flag[j]=1;
}
times++;
}
arr[count++]=arr[i];
}
cout<<"times="<<times<<"\n";
delete [] flag;
for (int m = 0; m < count; m++)
{
cout<<arr[m]<<" " ;
}
cout<<"\n" ;
system("pause");
return 0;
}