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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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'

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.