1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include<iostream>
using std::cout;
// returns the new shorter array length
int removeDups( int a[], int sz )
{
int currVal = a[0];// value to watch for duplicates of
int idxRead=1, idxWrite=1;// maintain separate index values to read and write positions
while( idxRead < sz )
{
if( a[idxRead] != currVal )
{
currVal = a[idxRead];// update current value
a[idxWrite] = currVal;// copy new value to current write position
++idxWrite;// advance write pointer
}
++idxRead;
}
return idxWrite;
}
int main ()
{
int nums[] = {1,1,2,3,3,3,4,5,6,6,7,8,8,8,9};// 15 elements
int SZ = sizeof( nums )/ sizeof( nums[0] );
int newSize = removeDups( nums, SZ );// new shorter length
cout << "newSize = " << newSize << '\n';// sb 9
for(int i=0; i<newSize; ++i)
cout << nums[i] << ' ';
cout << '\n';
return 0;
}
|