Reputation: 181
For the following code:
list<int> P;
int i,n,x;
cin>>n>>x;
for(i=0;i<n;i++)
P.push_back(i+1);
list<int>::iterator t2,t1=P.begin();
advance(t1,x-1);
t2=t1;
t1++;
P.erase(t1);
t2++;
cout<<*t2<<" ";
cout<<*(P.end())<<endl;
when the input I give is: 5 3,
the ouput comes out to be 5 4.
I am actually deleting the element 4 from the list. But it is going to the end of list. How do I avoid this? I want to completely remove 4 from the list so that the last element in the list is 5.
Upvotes: 0
Views: 187
Reputation: 1698
When you call the erase()
it deletes the element in the internal storage.
A test you can perform to test it is this:
int main()
{
vector<int> x = {3, 4, 5, 6};
int * temp = &x[1];
cout<<*temp<<endl;
x.erase(x.begin() + 1);
cout<<*temp<<endl;
}
The output shows:
4
5
Which shows the the erase removes the element and shifts all the elements in its spot.
Hope this helps.
Upvotes: 0
Reputation: 238351
Does erase() in C++'s STL actually delete the element?
Yes. erase
does destroy the element.
But it is going to the end of list.
*(P.end())
end
returns past the end iterator. Dereferencing it has undefined behaviour. You can use back
to get the last element.
Upvotes: 6