Sorry your browser is not supported!

You are using an outdated browser that does not support modern web technologies, in order to use this site please update to a new browser.

Browsers supported include Chrome, FireFox, Safari, Opera, Internet Explorer 10+ or Microsoft Edge.

Programming Talk / C++ / C# - std::vector erase or swap + pop back?

Author
Message
heyufool1
16
Years of Service
User Offline
Joined: 14th Feb 2009
Location: My quiet place
Posted: 11th Jan 2013 03:57 Edited at: 11th Jan 2013 03:57
Hello! I'm working on a C++ game and I have a small question regarding removing data from a vector. I'm currently using this method:


However, the same thing can be accomplished doing this:


My question is, which way is better (Specifically speed)? In this case the order of the vector doesn't matter so that's not a concern. Thanks for any input!

- Demo!
WLGfx
17
Years of Service
User Offline
Joined: 1st Nov 2007
Location: NW United Kingdom
Posted: 11th Jan 2013 13:51
Yep, you can erase more than one: http://www.cplusplus.com/reference/vector/vector/erase/

Mental arithmetic? Me? (That's for computers) I can't subtract a fart from a plate of beans!
Warning! May contain Nuts!
Dar13
17
Years of Service
User Offline
Joined: 12th May 2008
Location: Microsoft VisualStudio 2010 Professional
Posted: 12th Jan 2013 04:39 Edited at: 12th Jan 2013 04:40
What's wrong with
?

EDIT: Or maybe you want to extract the data from the vector before you clear it? I'm not really sure what you want to do here.

Jeff032
17
Years of Service
User Offline
Joined: 13th Aug 2007
Location:
Posted: 12th Jan 2013 05:06
erase() has a linear complexity (time increases linearly with the number of elements), since it shifts all the elements after the one that was deleted.

swap() and pop_back() both have a constant complexity (same amount of time regardless of the number of elements).

So theoretically, you would be better off with swap() and pop_back(), but you might not see much of a difference for smaller vectors.
heyufool1
16
Years of Service
User Offline
Joined: 14th Feb 2009
Location: My quiet place
Posted: 12th Jan 2013 06:34 Edited at: 12th Jan 2013 06:34
@WLGfx - I'm referring to the speed of the two methods.
@Dar13 - I only wanted to erase one item, not the whole vector.
@Jeff032 - Thanks for the information! Definitely makes sense now that the swap() and pop_back() would be slightly faster

- Demo!

Login to post a reply

Server time is: 2025-05-17 06:04:08
Your offset time is: 2025-05-17 06:04:08