Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an array element and shift the remaining ones

Tags:

c++

arrays

How do I remove an element of an array and shift the remaining elements down. So, if I have an array,

array[]={1,2,3,4,5}  

and want to delete 3 and shift the rest so I have,

array[]={1,2,4,5} 

How would I go about this in the least amount of code?

like image 456
user103572 Avatar asked May 18 '09 20:05

user103572


People also ask

How do you delete an element from an array and shift it?

Use System. arraycopy() to Remove Element From Array and Shift in Java. The System. arraycopy(Object src, int srcPos, Object dest, int destPos, int length) copies source array to destination array, starting the copy action from the position of the source to the position of the destination, till the given length.

How do you shift elements in an array to the left?

The array can be left rotated by shifting its elements to a position prior to them which can be accomplished by looping through the array and perform the operation arr[j] = arr[j+1]. The first element of the array will be added to the last of rotated array.

How do you remove an element from an array array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you remove an element from the middle of an array in Java?

You cannot delete elements from an array, you need to create new copy from the original one, and then return the result, or change the reference of the original array to the new copy.


1 Answers

You just need to overwrite what you're deleting with the next value in the array, propagate that change, and then keep in mind where the new end is:

int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};  // delete 3 (index 2) for (int i = 2; i < 8; ++i)     array[i] = array[i + 1]; // copy next element left 

Now your array is {1, 2, 4, 5, 6, 7, 8, 9, 9}. You cannot delete the extra 9 since this is a statically-sized array, you just have to ignore it. This can be done with std::copy:

std::copy(array + 3, // copy everything starting here           array + 9, // and ending here, not including it,           array + 2) // to this destination 

In C++11, use can use std::move (the algorithm overload, not the utility overload) instead.

More generally, use std::remove to remove elements matching a value:

// remove *all* 3's, return new ending (remaining elements unspecified) auto arrayEnd = std::remove(std::begin(array), std::end(array), 3); 

Even more generally, there is std::remove_if.

Note that the use of std::vector<int> may be more appropriate here, as its a "true" dynamically-allocated resizing array. (In the sense that asking for its size() reflects removed elements.)

like image 66
GManNickG Avatar answered Sep 28 '22 10:09

GManNickG