1.1刪除序列中相同的數

/*********************************************
*
*		c++程序設計實踐指導 
*
*		1.1刪除序列中相同的數
*
**********************************************/

#include <iostream>
using namespace std;
class ARR
{
	int m;		//數組實際元素個數
	int *p;		//存放原始數組及結果數組		
	int *c;		//存放記錄數據重複次數的數組
public:
	ARR (int x[],int size)		//構造函數,用size初始化m,用參數x初始化p
	{
		m = size;		
		p = new int[size];
		c = new int[size]();		//數組每一個元素初始化爲0
		for (int i = 0; i < m; i++)
		{
			p[i] = x[i];
		}
	}
	void delsame();		//完成刪除相同數據的功能
	void show()		//輸出到屏幕顯示
	{
		for (int i = 0; i < m; i++)
		{
			cout << p[i] << "\t";
		}
		cout << endl;
	}
	void count();		//完成統計每一個數據重複此處並輸出到屏幕的功能
};

void ARR::delsame()		//刪除相同數據
{
	int i,j;
	for(i = 0; i < m-1; i++)
	{
		if(p[i] == p[i + 1])		//若存在相同數據,則以後數據向前覆蓋
		{
			for(j = i+1; j < m-1;j++)
				p[j] = p[j+1];
			m--;
			i--;		//存在覆蓋後仍然有重複數據的可能,故要從當前i繼續斷定
		}
	}
	cout << endl;
}
void ARR::count()		//統計每一個數據的重複次數
{
	int i,j;
	int k = 0;
	for(i = 0; i < m; i++)
	{
		if(p[i] == p[i+1])		//若存在相同數據,則以後數據向前覆蓋
		{
			c[k] += 1;
			for(j = i+1; j < m; j++)
				p[j] = p[j+1];
			m--;
			i--;		//存在覆蓋後仍然有重複數據的可能,故要從當前i繼續斷定
		}
		else
		{
			c[k] += 1;		//按照平常計數習慣,爲每一個元素值加1
			cout << c[k] << "\t";
			k++;
		}
	}
	cout << endl;
}
int main()
{
	int b[16] = {1,2,2,3,4,4,5,6,6,7,8,8,8,9,10,10};		
	ARR v(b, sizeof(b)/sizeof(b[0]));
	v.show();		//顯示原數組
	v.delsame();
	v.show();		//顯示結果數組
	ARR w(b,sizeof(b)/sizeof(b[0]));
	w.count();		//顯示統計數組
	system("pause");
	return 0;
}
相關文章
相關標籤/搜索