I didn't understand why erase didn't work but pop back worked

programming
Tags: #<Tag:0x00007f2426dd23d0>

#1

I just made all the element which are not the given target go in front and after that I triied to erase the numbers after that but when I used A.erase(A.begin()+count,A.end()). it gave me errors but when I used pop_back N-count number of times it eventually worked. Can Any one explain this behavior


#2

Vector.erase() has O(n) time complexity, because after you delete the element, you need to(the library does it automatically) shift the successive elements to the right of the array. Hence, this is costly to use in a loop. In case of pop_back, after deleting that element, you don’t need to perform any other operations, and hence it is O(1).

Hope this helps!


#3

Using erase itself should resize the array automatically. I don’t understand why it gives wrong ans while using erase.


#4

while using A.erase(begin() + i) in for loop, update i=i-1 , too.