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

Tags: #<Tag:0x00007f2426dd23d0>


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


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!


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


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