std::inplace_merge
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <algorithm> 中定义
|
||
template< class BidirIt > void inplace_merge( BidirIt first, BidirIt middle, BidirIt last ); |
(1) | |
template< class BidirIt, class Compare> void inplace_merge( BidirIt first, BidirIt middle, BidirIt last, Compare comp ); |
(2) | |
合并两个连续的排序的范围
[first, middle)
,[middle, last)
成一个排序的范围[first, last)
。保证保留相等元素的顺序。 operator<的第一个版本使用比较的元素,第二个版本使用给定的比较函数comp
.原文:
Merges two consecutive sorted ranges
[first, middle)
and [middle, last)
into one sorted range [first, last)
. The order of equal elements is guaranteed to be preserved. The first version uses operator< to compare the elements, the second version uses the given comparison function comp
.目录 |
[编辑] 参数
first | - | 排序的第一范围的开头
原文: the beginning of the first sorted range |
middle | - | 排序的第一范围的结束和开始的第二个
原文: the end of the first sorted range and the beginning of the second |
last | - | 结束所述第二排序条件范围
|
comp | - | comparison function which returns true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b); The signature does not need to have const &, but the function must not modify the objects passed to it. |
类型要求 | ||
-BidirIt 必须满足 ValueSwappable 和 BidirectionalIterator 的要求。
| ||
-The type of dereferenced BidirIt must meet the requirements of MoveAssignable and MoveConstructible .
|
[编辑] 返回值
(无)
[编辑] 复杂度
究竟N-1比较,如果有足够的额外内存,否则N·log(N)其中N = std::distance(first, last).
原文:
Exactly N-1 comparisons if enough additional memory is available, otherwise N·log(N) where N = std::distance(first, last).
[编辑] 注释
该函数尝试分配一个临时缓冲区,通常是通过调用std::get_temporary_buffer。如果分配失败,效率低的算法选择.
原文:
This function attempts to allocate a temporary buffer, typically by calling std::get_temporary_buffer. If the allocation fails, the less efficient algorithm is chosen.
[编辑] 示例
下面的代码是一个实现归并排序.
原文:
The following code is an implementation of merge sort.
#include <vector> #include <iostream> #include <algorithm> template<class Iter> void merge_sort(Iter first, Iter last) { if (last - first > 1) { Iter middle = first + (last - first) / 2; merge_sort(first, middle); merge_sort(middle, last); std::inplace_merge(first, middle, last); } } int main() { std::vector<int> v{8, 2, -2, 0, 11, 11, 1, 7, 3}; merge_sort(v.begin(), v.end()); for(auto n : v) { std::cout << n << ' '; } std::cout << '\n'; }
输出:
-2 0 1 2 3 7 8 11 11
[编辑] 另请参阅
合并两个已排序的区间 (函数模板) | |
将区间按升序排序 (函数模板) | |
将区间内的元素排序,同时保持相等的元素之间的顺序 (函数模板) |