
Alexander
12.07.2017
09:57:46
Hi,
Would anyone be interested in adding std::shift to <algorithm>?
It would be similar to both:
- std::rotate, but without moving the head elements back to the tail. This would allow a more efficient implementation and clearer semantics in case rotation is not needed as well as correctness in case rotation is undesired.
- <algorithm>'s std::move/std::move_backward (depending on the shift direction).
std::shift should probably accommodate both left and right shifts by one of:
- giving it either begin() and end(), or rbegin() and rend(), similar to how std::rotate works for both left and right rotations. The advantage is compactness of the implementation.
- allowing the shift count parameter to be either positive or negative. The advantage is compactness, though it might not be clear which direction is which - to be consistent with rotate, positive integers should shift to the left.
- having std::shift_right and std::shift_left functions. The advantage is clarity when calling the methods, although the same argument could be made for having separate std::rotate_left and std::rotate_right instead of std::rotate, which we don't have.
Here's a sample implementation of a shift to the right direction:
template<class BidirIt>
void shift_right(BidirIt first, BidirIt last, unsigned int n = 1)
{
std::move_backward(first, last - n, last);
}
This demonstrates that while std::shift is implementable with std::move/std::move_backward,
1) It isn't immediately clear from the code (at least to my eyes) that this is a shift right, unless you are intimately familiar with std::move_backward.
2) Different calls, either to std::move or to std::move_backward, are required, depending on the shift direction.
So, implementing std::shift would allow writing more readable code.

Constantine
12.07.2017
10:10:14
нет, в дебуге хочется релизное заполнение памяти использовать, ибо слишком тормозит без оптимизации :)