Remove element from array c ++
You cannot "remove" an element from a C ++ array.
However, if the array consists of pointers, you can delete the object pointed to by a specific element.
In your case, the teacher is important to pay attention to new
whether the array objects are dynamically allocated (using an operator in C ++) or not. It can simply set its values 0
as an indicator that the value is no longer valid.
Without real source code, that's as much as possible.
source to share
If you are talking about a normal array. eg
int array[100];
then you cannot "remove" the element, since the array always contains 100 elements (in this example).
So it depends on your program's interpretation of the array values. If your teacher consistently uses the value 0 to denote a non-existent element, everything will work and just as correctly as any other approach.
source to share
You can remove an element from the vector in such a way that it is no longer there, and all other elements move 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
(assuming all the required headers are included, and the main body of the function, etc.).
Note that if you have a vector of pointers that were allocated new, you would need to call delete on the pointer before removing it from the vector. (It depends on whether the vector controls the lifetime of these pointers). If you have a boost :: shared_ptr vector then you won't need to manage the deletion.
source to share
:
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;
}
source to share
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 undefined by the C ++ standard. Even assignment to NULL, for example:
arr.at(3) = NULL;
2) If you really have to use pointers, use smart pointers (this specific case requires a shared_ptr):
std::vector< std::shared_ptr< int > > arr;
source to share