Bool remove from array by value

Was recently tasked with removing all instances of a value from an array with a boolean function. I have it working but was wondering if there was any way to write it better/optimize it, here is what I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  bool deleteValue(int list[], int target, int &size)
{
        // log original array size to see if it has changed
        const int originalSize = size;

        // search target in array
        int i;
        for (i = 0; i < size; i ++)
        {
                if (list[i] == target)
                {
                        // if target found in array
                        if (i < size)
                        {
                                // reduce the size of array and move all elements one space ahead
                                size = size - 1;
                                for (int j = i; j < size; j ++)
                                {
                                        list[j] = list[j + 1];
                                }
                        }
                }
        }

        if (originalSize == size)
        {
                return false;
        }

}


Would love to know if it could be improved upon.

The output should look like this:
1
2
3
4
5
6
7
8
9
10
11
Original array
[ 11, 2, 27, 34, 31, 78, 67, 91, 86, 10 ]

Target value 0 for removal is NOT in the list.
[ 11, 2, 27, 34, 31, 78, 67, 91, 86, 10 ]

Original array
[ 2, 63, 0, 56, 74, 44, 65, 0, 93, 68 ]

Target value: 0 is removed from the list.
[ 2, 63, 56, 74, 44, 65, 93, 68 ]
Had to implement it without helper functions, so no remove_it
Yes, it can be improved. Instead of copying the entire remaining array each time you delete one item, you should copy each item only once. For this problem, I find it easiest to keep two variables: one for the source item and once for the destination:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool deleteValue(int list[], int target, int &size)
{
        // log original array size to see if it has changed
        const int originalSize = size;

        // search target in array
        int src=0, dst=0;
        for (src = 0; src < size; src++) {
            if (list[src] == target) {
                cout << "Skip idx " << src << '\n';
                // Do nothing
            } else if (src != dst) {
                // You've already skipped something, so copy this one
                list[dst++] = list[src];
            } else {
                dst++;
            }
        }
        size = dst;
        return (originalSize != size);
}


Also, there are functions in the standard library to do this, but I assume that you're doing this as a learning experience.
Topic archived. No new replies allowed.