Why is std::rotate so fast?

前端 未结 2 595
野的像风
野的像风 2021-02-01 03:57

Why is std::rotate so much faster than the equivalent function that cplusplus.com describes?

cplusplus.com\'s implementation:

template 

        
2条回答
  •  滥情空心
    2021-02-01 04:00

    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!

提交回复
热议问题