Why is std::rotate
so much faster than the equivalent function that cplusplus.com describes?
cplusplus.com\'s implementation:
template
As the commentors already stated, it depends on your Standard Library implementation. But the code that you posted is valid even for forward iterators. As such, it imposes very little requirements (only that these iterators can be incremented and dereferenced).
Stepanov's classic Elements of Programming devotes an entire chapter (10) to rotate
and other rearrangement algorithms. For forward iterators, the series of swaps in your code gives O(3N)
assignments. For bidirectional iterators, three consecutive calls to reverse
yield another O(3N)
algorithm. For random access iterators, std::rotate
can be implemented as O(N)
assignments by defining a permutation of indices w.r.t. to the starting iterator first
.
All the above algorithms are in-place. Using a memory buffer, it is possible that the random access version can benefit from the greater cache locality of memcpy()
or memmove()
(if the underlying value type is POD) in which entire blocks of contiguous memory can be swapped. If your insertion sort is done on an array or std::vector
, it is likely that your Standard Library will take advantage of this optimization.
TL;DR: trust your Standard Library and don't reinvent the wheel!