1

i am trying to write a code that will delete all the elements if an array has same element at different index . it works fine for one element deletion or elements at odd index i.e 1,3,5 etc but it neglects one element if the consecutive index have same element.

i have just tried this to get my hands on arrays

for(int i=0;i<n;i++)                                     //for deletion
    {
        if(arr[i]==_delete)
        {   
            arr[i]=arr[i+1];
           --n;

        }

    }
3
  • 1
    iterate from the back, then it should work Commented Oct 14, 2019 at 14:16
  • 1
    Start by using std::vector instead of arrays? Will make your life much simpler. Commented Oct 14, 2019 at 14:16
  • 5
    There is a standard algorithm for this: std::remove_if Commented Oct 14, 2019 at 14:22

2 Answers 2

2

I suggest you use std::vector as a container for your objects.

std::vector<TYPE> vec ;
// initialise vector

You can use

vec.erase(std::remove_if(vec.begin(), vec.end(),
                          [](const auto & item){return item == _delete;}), vec.end());

Alternatively, you can use std::list. Its list::erase has linear time complexity.

Sign up to request clarification or add additional context in comments.

Comments

2

As an additional solution, if you want to deal with built-in C++ arrays, the standard std::remove algorithm can be rewritten like this:

void remove(int _delete) {
    int j = 0;
    for (int i = 0; i < n; ++i) {
        if (arr[i] != _delete) {
            arr[j++] = arr[i];
        }
    }
    // update the size!
    n = j;
}

It's quite pretty:

We keep in the array the elements we only need, and override the ones in which we are not interested (they can be either equal or not to _delete and start at position j till the end)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.