Please tell me how to delete an element from a C++ array.
My teacher is setting its value to 0, is that correct?
Setting it to zero will still make that zero appear when you iterate over the array, or when you access it by index. If you do not want that, you have to copy all elements after the one you deleted one step towards the beginning of the array.
If you're talking about a normal array, e.g.
int array[100];
then you can't "delete" an element, since the array always has 100 elements (in this example).
So it depends on the interpretation your program makes of the array values. If your teacher is consistently using a value of 0 to mean non-existent element, everything will work and so that's as correct as any other approach.
You can remove an element from a vector such that the element is no longer there and all the other elements shift a position.
struct counter
{
int x;
int operator()() { return x++; }
counter() : x(0) {}
};
std::vector<int> v;
std::generate_n( std::back_inserter(v), 8, counter() );
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(cout, " "));
std::cout << '\n';
v.erase( v.begin() + 4 );
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(cout, " "));
std::cout << '\n';
Should output:
0 1 2 3 4 5 6 7
0 1 2 3 5 6 7
(assume all necessary headers included and main function body etc).
Note that if you have a vector of pointers which were allocated with new, you would have to possibly call delete on the pointer before it was erased from the vector. (This depends on whether the vector manages the lifetime of these pointers). If you have a vector of boost::shared_ptr you will not need to manage the deletion.
cin>>n;
int array[n];
...
...
for(int k=0;k<n;k++){
array[k]=array[k+1]; //overwriting the current element of array with next element
array[n-1]=0; //setting last element as 0
--n; //reducing the size of array
}
...
...
it's an old topic but I'm gonna put this answer here for anyone who's recently seen this question!
deleting an element from the array is a heavy operation you can easily keep track of your elements with an index. anyway, you can call this function whenever you want to delete the first x element of a vector.
vector<int> remove_frist_x_items(const vector<int>& arr, int x)
{
return vector<int>(arr.begin() + x, arr.end());
}
// Delete the first element from the array
auto new_array = remove_frist_x_items(the_old_one, 1);