i have a function that removes duplicates from an array, but how do i get the new compacted array back? the compacted array should only have 4 int's.
thanks
//remove duplicates from array
void compactArray(int arr[], const int size){
int j=0;
int lastVal=0;
for (int i=0;i<size;i++) {
if (arr[i] != lastVal) {
arr[j] = arr[i];
++j;
}
lastVal = arr[i];
}
}
int main() {
int ar[] = {1, 2, 3, 3, 3, 4, 4};
int sizeAr=sizeof(ar)/sizeof(ar[0]);
compactArray(ar, sizeAr);
}
You may have the same array but you should return from the function the last position of unique elements.
For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int compactArray( int arr[], int size )
{
int j = 0;
for ( int i = 1; i < size; i++ )
{
if ( arr[j] != arr[i] )
{
arr[++j] = arr[i];
}
}
return ( ++j );
}
Here 'j' is position where unique elements end. So in main you can write
1 2 3 4
int last = compactArray( a, sizeof( a ) / sizeof( *a ) );
for ( int i = 0; i < last; i++ ) std::cout << a[i] << ' ';
std::cout << std::endl;