remove an item from an array and return the new array in C++

Hi, experts,

I have an question in C++.

Basically, we want to kick out an item in an array and return the rest.

such as:
originalArray = {1, 2, 3, 4, 5, 6} and kick out the item in position 3, which is originalArray[3] = 4, and the result is {1, 2, 3, 5, 6}

I image a function like this, it takes two variables, the first is an array, the second is a position, such as:

kickOne(OriginalArray, 3)

and return another array. We may or may not know the size of original array.

Please help.
Who is Participating?
HooKooDooKuConnect With a Mentor Commented:
First of all, you likely do not want to return an array.  While it is not impossible for a function to return 'large' items (like an array or a C++ class object), because of the overhead involved, you generally want to limit having a function return one simple variable.

But you can still "return an array" in "one simple variable" if what you return is a pointer.

However, you don't exactly specify if what you want is a new copy of the original array, or if you want to modify the existing array instead.

Since you say you want to return an array, then you could have something that looks like the following pseudo code:

int* KickOne( int Org[], int Pos, int Size )
  int* rc = new int[ Size - 1 ];
  for loop to copy elements from Org[i] to rc[i] that come before Pos
  for loop to copy elements from Org[i+1] to rc[i] that come after Pos
  return rc;

Open in new window

The function take an array of integers, a Position, and a size of the array.
The function creates a new array of integers off the heap and copies everything from the original array minus the item at the given Position.
The function then returns a pointer to the new array.
Since the array was allocated with 'new', you would need to make sure the calling function eventually destroys it with 'delete'
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.