1

Please tell me how to delete an element from a C++ array.

My teacher is setting its value to 0, is that correct?

6
  • 10
    Can you provide some code to illustrate? What exactly do you mean by delete? Commented Oct 26, 2010 at 11:02
  • Do you mean delete as in the keyword delete? Or do you mean simply removing an element from an array? Do you have an array of pointers, or an array of objects? Commented Oct 26, 2010 at 11:03
  • You're going to have to provide some code to clarify what you mean. A "C++" array is technically no different than a C array: e.g. int foo[30]; But there are many different ways to implement an array in C++. Commented Oct 26, 2010 at 11:03
  • its a simple shopping bill system ..where one can remove a purchased product from the list of products stored in an array.. Commented Oct 26, 2010 at 11:13
  • @Krishna: You need to show some code. One cannot "set an array to 0". One can, however, set a pointer referring to the first element in a (possibly dynamically allocated) array to 0. And one can do all kinds of other things. So you need to show us some code, or you likely won't get a meaningful answer. Commented Oct 26, 2010 at 11:29

11 Answers 11

9

You can't really "delete" an element from a C++ array.

However, if the array consists of pointers, you can delete the object that a specific element points to.

In your teacher's case, it will be important to make note of whether the objects of the array are dynamically allocated (using the new operator in C++) or not. He may simply be setting his values to 0 as an indicator that the value is no longer valid.

Without actual source code, this is as much as I can help you with.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

can't he put a pointer to the last element and just call "delete pointer"?
2

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.

1 Comment

re: your counter predicate: The standard does not make any guarantees about how often the predicate is copied. You need to externalise the mutable state, e.g. by having int x declared outside and counter only storing a reference to it. There's still the order-of-application problem, but it's probably not a problem for std::generate. Seminal paper: gotw.ca/gotw/052.htm
1

If the array is not intended to be sorted, a quick and easy way is to copy the last element to the position of the element to be deleted, then reduce the element count by 1.

Comments

1
   :
    int main()
{   
    int a[100],x,i;
    cout<<"enter the no. of elements(max 100): ";
    cin>>x;
    for(i=0;i<x;i++)
    {
        cout<<"enter "<<i+1<<" element: ";
        cin>>a[i];
        cout<<endl;
    }
    cout<<"your array: "<<endl;
    for(i=0;i<x;i++)
    {
        cout<<a[i]<<endl;
    }
    cout<<"enter the element you want to delete: ";
    int b,flag,pos;
    cin>>b;
    for(i=0;i<x;i++)
    {
        if(b==a[i])
        {
            flag=1; pos=i;
        }
        else
        {
            flag=0;
        }
    }
    if(flag==0)
    {
        cout<<"element not found nothing to delete....";
    }
    for(i=0;i<x-1;i++)
    {
        if(i<pos)
        {
            a[i];
        }
    else if(i>=pos)
    {
        a[i]=a[i+1];
    }
    }
    cout<<"new array:"<<endl;
    for(i=0;i<x-1;i++)
    {
        cout<<a[i]<<endl;
    }
    return 0;
}

1 Comment

This code isn't indented properly, and there is a spurious colon at the beginning. You should explain, too, that this works by shifting leftwards the elements found to the right of the one you delete, and that therefore you need to keep track of the current length of the array. Plus, if anyone goes as far as implementing this, using std::vector in the first place would be better.
0

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.

Comments

0

1) If you have an array of pointers, then like this :

// to create an array :
std::vector< int* > arr( 10, NULL );
for ( std::vector< int* >:iterator it=arr.begin; arr.end() != it; ++ it )
{
  *it = new int( 20 );
}
// to delete one element
delete( arr.at(3) );

Any access to this array element is formally an undefined behaviour by the c++ standard. Even assignment of NULL, like this:

arr.at(3) = NULL;

2) If you really must use pointers, then use smart pointers (this specific case requires shared_ptr) :

std::vector< std::shared_ptr< int > > arr;

Comments

0
scanf("%ld",&x);//x position where we have to delete
if(x==n-1) {
   n-=1;

}
else {
   n-=1;
   for (int i = x; i < n; i++) {
        /* code */
        A[i]=A[i+1];
   }
}

1 Comment

Code requires some commenting, and answer requires some explanations.
0

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);

Comments

0

You can make another array by copying all the other element except the one you need to delete. And just delete the previous array using the below code line. (let's assume arr_name is the name of the array. if your array is like this,

int* arr_name = new int[5]; 

Then delete it using

delete[] arr_name; 

Comments

-2
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
}
...
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.