std::rotate
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <algorithm> 中定义
|
||
template< class ForwardIt > void rotate( ForwardIt first, ForwardIt n_first, ForwardIt last ); |
(至 C++11) (C++11 起) |
|
以这样的方式的范围内
[first, last)
交换中的元素,该元素n_first
成为新的范围的第一个元素和n_first - 1
成为最后一个元素. 原文:
Swaps the elements in the range
[first, last)
in such a way, that the element n_first
becomes the first element of the new range and n_first - 1
becomes the last element. 目录 |
[编辑] 参数
first, last | - | 元素的范围旋转
|
n_first | - | 元素移动到新的范围的开始
原文: the element to move to the beginning of the new range |
类型要求 | ||
-ForwardIt 必须满足 ValueSwappable 和 ForwardIterator 的要求。
| ||
-The type of dereferenced ForwardIt must meet the requirements of MoveAssignable and MoveConstructible .
|
[编辑] 返回值
迭代器等于
first + (last - n_first)
(C++11 起)原文:
The iterator equal to
first + (last - n_first)
(C++11 起)[编辑] 复杂度
线性
first
和last
之间的距离原文:
linear in the distance between
first
and last
[编辑] 可能的实现
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 = n_first; } else if (first == n_first) { n_first = next; } } } |
[编辑] 示例
的std ::旋转在许多算法是一种常见的构建块。这个例子演示了插入排序C + +
原文:
std::rotate is a common building block in many algorithms. This example demonstrates insertion sort in C++
#include <vector> #include <iostream> #include <algorithm> int main() { std::vector<int> v{2, 4, 2, 0, 5, 10, 7, 3, 7, 1}; std::cout << "before sort: "; for(int n: v) std::cout << n << ' '; std::cout << '\n'; // insertion sort for (auto i = v.begin(); i != v.end(); ++i) { std::rotate(std::upper_bound(v.begin(), i, *i), i, i+1); } std::cout << "after sort: "; for(int n: v) std::cout << n << ' '; std::cout << '\n'; // simple rotation to the left std::rotate(v.begin(), v.begin() + 1, v.end()); std::cout << "simple rotate left : "; for(int n: v) std::cout << n << ' '; std::cout << '\n'; // simple rotation to the right std::rotate(v.rbegin(), v.rbegin() + 1, v.rend()); std::cout << "simple rotate right : "; for(int n: v) std::cout << n << ' '; std::cout << '\n'; }
输出:
before sort: 2 4 2 0 5 10 7 3 7 1 after sort: 0 1 2 2 3 4 5 7 7 10 simple rotate left : 1 2 2 3 4 5 7 7 10 0 simple rotate right: 0 1 2 2 3 4 5 7 7 10
[编辑] 另请参阅
将区间内的元素旋转并复制 (函数模板) |