C++ Algorithm rotate()

2024年8月30日 | 5分钟阅读

C++ Algorithm rotate() 函数用于旋转范围 [first, last) 内元素的顺序。

  • 序列将从源序列中间的元素开始,最后一个元素将紧随第一个元素之后。
  • 从中间元素到中间元素与最后一个元素之间的元素。

语法

参数

first:一个前向迭代器,指向要旋转的范围中第一个元素的位置。

middle:一个前向迭代器,指向范围 [first, last) 内的元素,该元素将被移动到范围中的第一个位置。

last:一个前向迭代器,指向正在反转元素的范围中最后一个元素的后一个位置。

返回值

复杂度

复杂度与范围 [first, last) 成线性关系:交换或移动元素直到所有元素都被重新定位。

数据竞争

范围 [first, last) 中的对象被修改。

异常

如果元素交换或移动或迭代器操作抛出异常,则此函数会抛出异常。

请注意,无效参数会导致未定义行为。

示例 1

让我们来看一个简单的例子来旋转给定的字符串

输出

Before Rotate : Hello
After Rotate  : lloHe

示例 2

让我们看另一个简单示例

输出

Original order : 1. A   2. B   3. C   4. D   5. E   6. G   7. H   
Rotate with 'C' as middle element
Rotated order  : 1. C   2. D   3. E   4. G   5. H   6. A   7. B   
Rotate with 'G' as middle element
Rotated order  : 1. G   2. H   3. A   4. B   5. C   6. D   7. E   
Rotate with 'A' as middle element
Original order : 1. B   2. C   3. D   4. E   5. G   6. H   7. A   

示例 3

让我们看另一个简单示例

输出

Old vector : 1 2 3 4 5 6 7 8 9
New vector after left rotation : 4 5 6 7 8 9 1 2 3

Old vector : 1 2 3 4 5 6 7 8 9
New vector after right rotation : 6 7 8 9 1 2 3 4 5

示例 4

让我们看另一个简单示例

输出

Vector v1 is ( -3 -2 -1 0 1 2 3 4 5 ).
After rotating, vector v1 is ( 0 1 2 3 4 5 -3 -2 -1 ).
The original deque d1 is ( 0 1 2 3 4 5 ).
After the rotation of a single deque element to the back,
 d1 is   ( 1 2 3 4 5 0 ).
After the rotation of a single deque element to the back,
 d1 is   ( 2 3 4 5 0 1 ).
After the rotation of a single deque element to the back,
 d1 is   ( 3 4 5 0 1 2 ).
After the rotation of a single deque element to the back,
 d1 is   ( 4 5 0 1 2 3 ).
After the rotation of a single deque element to the back,
 d1 is   ( 5 0 1 2 3 4 ).
After the rotation of a single deque element to the back,
 d1 is   ( 0 1 2 3 4 5 ).

下一主题C++ 算法