Search code examples
c++arraysduplicates

Delete duplicates from array C++


I am trying to create a simple program which calls on 2 functions.
The first function takes a partially filled array, loops through it and deletes any duplicate values. When a value is deleted from the array, the remaining numbers are moved backwards to fill the gap i.e. when the function is finished, all null values of the array will be together at the end.

The second function prints the updated array.

My current code is below. At present when I run my code, the console shows:
2 6 0 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460.
It should be showing:
1 2 5 6

Also, I am not sure how to move the remaining elements of the array backwards so that the null values will be together at the end.

#include <iostream>

using namespace std;

void deleteRepeats(int *arr, int arraySize, int& posUsed);
void printArray(int *arr, int arraySize);

int main()
{
    int arr[10] = { 1, 2, 2, 5, 6, 1};
    int posUsed = 6;
    int arraySize = 10;


    deleteRepeats(arr, arraySize, posUsed);
    printArray(arr, arraySize);

    return 0;
}

void deleteRepeats(int *arr, int arraySize, int& posUsed)
{
    for (int i = 0; i < arraySize; i++)
    {
        for (int j = i; j < arraySize; j++)
        {
            if (arr[i] == arr[j])
            {
                for (int k = j; k < arraySize; k++)
                {
                    arr[k] = arr[k + 1];

                }
                posUsed--;
            
            }
            else
                j++;
        }
    }
}

void printArray(int *arr, int arraySize)
{
    for (int i = 0; i < arraySize; i++)
    {
        cout << arr[i] << "  ";
    }
}

Solution

  • Given your assignment constraints (more C-like, than idiomatic C++), you can rewrite your function like this, to make it work:

    void deleteRepeats(int *arr, int arraySize, int& posUsed)
    {
        for (int i = 0; i < posUsed; ++i)
        {
            int duplicates = 0;
            int j = i + 1;
            // find the first duplicate, if exists
            for ( ; j < posUsed; ++j)
            {
                if ( arr[i] == arr[j] ) {
                    ++duplicates;
                    break;
                }
            }
            // overwrite the duplicated values moving the rest of the elements...
            for (int k = j + 1; k < posUsed; ++k)
            {
                if (arr[i] != arr[k])
                {
                    arr[j] = arr[k];
                    ++j;
                }
                // ...but skip other duplicates
                else
                {
                    ++duplicates;    
                }
            }
            posUsed -= duplicates;
        }
        // clean up (could be limited to the duplicates only)
        for (int i = posUsed; i < arraySize; ++i)
            arr[i] = 0;
    }