5 ms·
Specifically in the case of a self-swap, which is a somewhat odd thing to do in the first place.
by hendzen 11y ago
Specifically in the case of a self-swap, which is a somewhat odd thing to do in the first place.
- boulos 11y agoBefore shrink to fit, you could easily have produced this with a few references and a "use std::swap unconditionally". The std::swap thing is only one pitfall, the reliance on "our memcpy will do the right thing with any overlap" is a bit risky (and doesn't hold with LD_PRELOAD, but I think it may have been switched to using the LLVM based librt project anyway, that is I'm not sure these calls are supposed to become naked memcpy).
- AnthonyMouse 11y agoIt's quite common actually. Usually in the context of something like "swap element 'n' with the last element in this vector" without any check to see if 'n' is already the last element, because checking for that condition just to avoid a harmless no-op in the uncommon case is ugly and slower in the common case.
- dkopi 11y agoImagine reversing a string: while(pStart <= pEnd) swap(*pStart++, *pEnd--); If swap doesn't work for a self swap, this code would break in the case of an odd length string. It's an easy fix in this case, but being able to swap an element with itself is convenient.
- Matheus28 11y agoA more common case, would be swapping a vector element with the back of the vector and popping it off, which is kinda common.
- plorkyeran 11y agoIt was common pre-C++11, but these days you should just be doing a move and pop rather than a swap and pop.
- adrianN 11y agoLuckily all existing code has been modernized to C++11 /s.