Rotation and permutation
Remember our code from Swapping, reversing, and partitioning to reverse the order of words in a sentence? When the "sentence" contains only two words, there is another way to look at the reversal: you could consider it a cyclic rotation of the elements in the underlying range. std::rotate(a,mid,b)
rotates the elements of the range [a,b)
so that the element formerly addressed by mid
is now at a
(and returns an iterator pointing to the element whose value was formerly at a
):
template<class FwdIt> FwdIt rotate(FwdIt a, FwdIt mid, FwdIt b) { auto result = a + (b - mid); // First, reverse the whole range. std::reverse(a, b); // Next, un-reverse each individual segment. std::reverse(a, result); std::reverse(result, b); return result; } void test() { std::vector<int> v = {1, 2, 3, 4, 5, 6}; auto five = std::find(v.begin(), v.end(), 5); auto one = std::rotate(v.begin(), five...