7.旋转
- rotate(): 将容器中的元素看成一个环,
- rotate_copy():产出一个旋转后的副本
函数模板为:
//rotate
template<class ForwardIt>
void rotate(ForwardIt first, ForwardIt n_first, ForwardIt last)
{
ForwardIt next = n_first;
while (first != next) {
std::swap(*first++, *next++);
if (next == last) {//next指向末尾[first,last)右开位置,重新定位
next = n_first;
} else if (first == n_first) {
n_first = next;
}
}
}
//rotate_copy
template<class ForwardIt, class OutputIt>
OutputIt rotate_copy(ForwardIt first, ForwardIt n_first,
ForwardIt last, OutputIt d_first)
{
d_first = std::copy(n_first, last, d_first);//复制后半截
return std::copy(first, n_first, d_first);//将前半截复制到目标位置的后半截,完成旋转
}
例子:
---------------省略----------------
vector<int> vec1 = {1,2,3,4,5,6};
vector<int> vec2;
rotate(vec1.begin(), vec1.begin() + 3, vec1.end());
---------------省略----------------
rotate_copy(vec1.begin(), vec1.begin() + 3, vec1.end(), back_inserter(vec2));
---------------省略----------------
输出结果为:
vec1: 4 5 6 1 2 3
vec2: 1 2 3 4 5 6