std::partition
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <algorithm> 中定义
|
||
template< class BidirIt, class UnaryPredicate > BidirectionalIterator partition( BidirIt first, BidirIt last, |
(至 C++11) (C++11 起) |
|
重新排序的范围
[first, last)
在这样一种方式中的元素,所有元素的谓词p
回报true之前的元素为谓词p
回报false。不保留元素的相对顺序. 原文:
Reorders the elements in the range
[first, last)
in such a way that all elements for which the predicate p
returns true precede the elements for which predicate p
returns false. Relative order of the elements is not preserved. 目录 |
[编辑] 参数
first, last | - | 范围内的元素进行重新排序
|
p | - | unary predicate which returns true 如果该元素的,要责令之前的其他元素 . 原文: if the element should be ordered before other elements The signature of the predicate function should be equivalent to the following: bool pred(const Type &a); The signature does not need to have const &, but the function must not modify the objects passed to it. |
类型要求 | ||
-BidirIt 必须满足 BidirectionalIterator 的要求。
| ||
-ForwardIt 必须满足 ValueSwappable 和 ForwardIterator 的要求。 However, the operation is more efficient if ForwardIt also satisfies the requirements of BidirectionalIterator
|
[编辑] 返回值
第二组的第一个元素的迭代器,.
原文:
Iterator to the first element of the second group.
[编辑] 复杂度
究竟last-first应用程序的谓词和最last-first掉期。
ForwardIt
符合要求的BidirectionalIterator
(last-first)/2掉期做.原文:
Exactly last-first applications of the predicate and at most last-first swaps. If
ForwardIt
meets the requirements of BidirectionalIterator
at most (last-first)/2 swaps are done.[编辑] 可能的实现
template<class BidirIt, class UnaryPredicate> BidirIt partition(BidirIt first, BidirIt last, UnaryPredicate p) { while (1) { while ((first != last) && p(*first)) { ++first; } if (first == last--) break; while ((first != last) && !p(*last)) { --last; } if (first == last) break; std::swap(*first++, *last); } return first; } |
[编辑] 示例
#include <algorithm> #include <functional> #include <iostream> #include <iterator> #include <vector> bool is_even(int i) { return i % 2 == 0; } int main() { std::vector<int> v; for (int i = 0; i < 10; ++i) v.push_back(i); std::cout << "Original vector:\n "; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); // Partition the vector std::vector<int>::iterator p = std::partition(v.begin(), v.end(), std::ptr_fun(is_even)); std::cout << "\nPartitioned vector:\n "; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\nBefore partition:\n "; std::copy(v.begin(), p, std::ostream_iterator<int>(std::cout, " ")); std::cout << "\nAfter partition:\n "; std::copy(p, v.end(), std::ostream_iterator<int>(std::cout, " ")); }
Possible output:
Original vector: 0 1 2 3 4 5 6 7 8 9 Partitioned vector: 0 8 2 6 4 5 3 7 1 9 Before partition: 0 8 2 6 4 After partition: 5 3 7 1 9
[编辑] 另请参阅
(C++11) |
判断区间是否被给定的谓词划分 (函数模板) |
将元素分为两组,同时保留其相对顺序 (函数模板) |