-1

I'm new to c++ and I'm writing an array manipulator program. How would you write a function that removes an element from an array? What parameters would you pass to it? The function cannot have any cout or cin statements, they must be in main instead. How would you call the function? I wrote a function for adding an element to an array, and it looks like this:

int insertValue(int arr[], int value, int pos, int size)

if (size == 10)
    cout << "Array full" << endl;
else
{
    int i;
    for (i = size - 1; i >= pos; --i) {
        arr[i + 1] = arr[i];
    }
    arr[pos] = value;
    ++size;
}
cout << endl;
return size;

This function works when called. Would removing an element from an array and moving everything to the left follow the same layout? This is what I have so far for that function:

int removeValue(int arr[], int value, int pos, int size)

for (int i = pos; i < size; ++i) {
array[i] = array[i + 1]; 
}
arr[pos] = value;
return size;

I don't think I have the right idea for this code, which is why I am confused. Can someone explain the idea behind this function and how it would be written correctly?

Thanks for your help!

  • 1
    If you're new to C++, a resource better for you than Stack Overflow questions would be a [good book](http://stackoverflow.com/q/388242/1782465). – Angew is no longer proud of SO Apr 08 '17 at 10:08
  • 2
    An array have a fixed size, set at compilation-time. You can't *remove* an element from an array. – Some programmer dude Apr 08 '17 at 10:08
  • 2
    Hi Sabina. There is a general expectation here that questions are proceeded by some prior personal effort first. We have so many people asking for free work that we advise posters to show what they have tried/researched, so as to differentiate their question from posters who intend to make no effort at all. Hope that helps! – halfer Apr 08 '17 at 10:10
  • Thanks for your edit, much better. I have voted to reopen. – halfer Apr 13 '17 at 15:23

2 Answers2

2

Use std::vector or std::array instead of c-array([]). To remove elements from container, you should use std::vector + std::remove + std::vector::erase

Sild
  • 3,077
  • 3
  • 15
  • 21
0

This line is going to overflow the array, with all the attended horrors, as you are indexing one past the end.

array[i] = array[i + 1]; 

But other than that as long as you keep track of how many elements your array has it should be OK

Delete Me
  • 102
  • 2