
February 29th, 2004, 11:59 PM
|
|
Registered User
|
|
Join Date: Mar 2003
Posts: 2
Time spent in forums: < 1 sec
Reputation Power: 0
|
|
|
c++, removing repeat entries in arrays
I know this is fairly simple, I just can't get it to work like I know it should. What I need is a function that removes repeat entries in an array.
Explanation/Example:
Code:
char a[10];
a[0] = 'a';
a[1] = 'b';
a[2] = 'a';
a[3] = 'c';
int size = 4;
removeRepeats(a, size);
In that example, removeRepeats() should detect the second 'a', remove it, and close the gap.
This is what I have so far for the function. It works for the example above, but not if the array is altered in any way.
Code:
void removeRepeats(char a[], int& size)
{
int numReps = 0;
int newsize;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(a[i] == a[j])
{
//a[j] = "";
for(int k=j+1;k<size;k++)
{
a[k-1] = a[k];
newsize = k;
}
numReps++;
a[size-1] = a[size];
}
}
}
size = newsize;
cout << "- Begin Array - size: " << size << endl;
for(int l=0;l<size;l++)
{
cout << a[l] << endl;
}
cout << "- End Array -" << endl << endl;
cout << "Number of repeats: " << numReps << endl;
}
What am I overlooking? Please help, thanks!
Ty
|