-4

I just try to make a code to erase duplicate numbers from the array but I can't shrink the array size after erase the number. Here is my code:

for (i=0;i!=n;i++)
{
    for (j=i+1; j!=n; j++)
    {
        if(arr[i]==arr[j])
        {
            while(j!=n-1)
            {
                arr[j]=arr[j+1];
                j++;
            }
            n--;
        }
    }
}

It's not crash but it's not running either so I have no idea what go wrong.

H.Viet
  • 3
  • 1
  • Use a `std::vector` instead of a raw array. – user0042 Dec 03 '17 at 03:25
  • But I'm practice using array now so I have to use it. – H.Viet Dec 03 '17 at 03:27
  • 2
    [You're getting fooled](https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr) regarding the _"practice"_. – user0042 Dec 03 '17 at 03:28
  • And then use [`std::remove()`](http://en.cppreference.com/w/cpp/algorithm/remove) to move duplicates to the end of the vector, and then [`std::vector::erase()`](http://en.cppreference.com/w/cpp/container/vector/erase) to delete them from the vector. This is known as the [Erase-Remove idiom](https://en.wikipedia.org/wiki/Erase–remove_idiom) – Remy Lebeau Dec 03 '17 at 03:28
  • You need to go through and find how many elements are duplicates then declare an array which is the array size less that number. Finally only place the non duplicates into a the new array – Jake Freeman Dec 03 '17 at 03:41
  • *but I can't shrink the array size* -- Arrays cannot have their sizes changed. All you can do is change or rearrange elements in an array. If you truly want to shrink the size, use `std::vector` instead of an array. – PaulMcKenzie Dec 03 '17 at 07:34

1 Answers1

0

You should use another var for moving next elements to its prev positions. And after removal, you should start searching from the same j position.

for (i=0;i!=n;i++)
{
    for (j=i+1; j!=n; j++)
    {
        if(arr[i]==arr[j])
        {
            int k = j;
            while(k != n-1)
            {
                arr[k]=arr[k+1];
                k++;
            }
            n--;
            --j;
        }
    }
}
abdullah
  • 662
  • 5
  • 7