Home > Mobile >  How can I modify the code fragment in order to remove all specified elements from array in c ?
How can I modify the code fragment in order to remove all specified elements from array in c ?

Time:03-27

I have this code

#include <iostream>
    
using namespace std;
     
int deleteElement(int mas[], int pos, int x)
{
    int i;
    for (i = 0; i < pos; i  )
        if (mas[i] == x)
            break;
     
    if (i < pos)
    {
        pos = pos - 1;
        for (int j = i; j < pos; j  )
            mas[j] = mas[j   1];
    }
     
    return pos;
}
     
int main()
{
    const int N = 4;
    int mas[N] = {2, 6, 6, 8};
    int pos = sizeof(mas)/sizeof(mas[0]);
    int x = 6;
     
    pos = deleteElement(mas, pos, x);
     
    cout << "Modified array is \n";
    for (int i = 0; i < pos; i  )
        cout << mas[i] << " ";
     
    return 0;
}

The task is to remove all specified elements from array. In my case x = 6 but it only removes one element that is equal to x:

Array: 2 6 6 8
Output: 2 6 8

What I need to do to make this code remove all elements from array that are equal to x?

Expected output: 2 8

CodePudding user response:

Using remove_if is probably the best solution here, but assuming you aren't allowed to use it, then you need to keep track of whether an item was removed, and how many elements are being removed. Currently, you find the first element, then modify the array to remove only that element.

Using your method, you could make the function loop when pos changes (though, I don't really recommend this solution, it would work). Like so:

int deleteElement(int mas[], int pos, int x)
{
    int prevPos;
    do {
        prevPos = pos;
        int i;
        for (i = 0; i < pos; i  )
            if (mas[i] == x)
                break;
        
        if (i < pos)
        {
            pos = pos - 1;
            for (int j = i; j < pos; j  )
                mas[j] = mas[j   1];
        }
    } while ( prevPos != pos ); // if the size has changed, loop back to beginning
    
    return pos;
}

Alternatively, you can just keep track of how many items were removed, and shift elements up by that amount, like so:

int deleteElement(int mas[], int pos, int x)
{
    int idx;
    int offset = 0; // number of elements to shift by
    for ( int idx = 0; idx < pos;   idx ) {
        if ( mas[idx] == x ) // found the element
              offset;        // so increase the offset
        else if ( offset != 0 ) { // doesn't really need the "if" part, but would be more efficient if dealing with objects
            mas[idx-offset] = mas[idx]; // move the item up the list
        }
    }
    
    return pos - offset; // new size is the old size minus number of elements removed
}
  •  Tags:  
  • c
  • Related