Please tell me how to delete an element from a C++ array.
My teacher is setting its value to 0, is that correct?
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.
:
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;
}
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.
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;
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;
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];
}
}