std::partition
出自cppreference.com
| 在標頭 <algorithm> 定義
|
||
| |
(1) | (C++20 起為 constexpr) |
| |
(2) | (C++17 起) |
1) 重排序範圍
[first, last) 中的元素,使得謂詞 p 對其返回 true 的所有元素位於謂詞 p 對其返回 false 的所有元素之前。不保持相對順序。2) 同 (1),但按照
policy 執行。 此重載只有在滿足以下所有條件時才會參與重載決議:
|
|
(C++20 前) |
|
|
(C++20 起) |
如果 *first 的類型不可交換 (Swappable) (C++11 前)ForwardIt 不可交換值 (ValueSwappable) (C++11 起),那麼行為未定義。
參數
| first, last | - | 要重排序的元素範圍的迭代器對 |
| policy | - | 所用的執行策略 |
| p | - | 如果元素在順序中應該在其他元素之前則返回 true 的一元謂詞。對每個(可為 const 的) |
| 類型要求 | ||
-ForwardIt 必須滿足老式向前迭代器 (LegacyForwardIterator) 。
| ||
-UnaryPred 必須滿足謂詞 (Predicate) 。
| ||
返回值
指向第二組元素中首元素的迭代器。
複雜度
給定 N 為 std::distance(first, last):
1) 應用 N 次
p。2) 應用 O(N) 次
p。 交換 O(N·log(N)) 次。
異常
擁有名為 ExecutionPolicy 的模板形參的重載按下列方式報告錯誤:
- 如果作為算法一部分調用的函數的執行拋出異常,且
ExecutionPolicy是標準策略之一,那麼調用 std::terminate。對於任何其他ExecutionPolicy,行為由實現定義。 - 如果算法無法分配內存,那麼拋出 std::bad_alloc。
可能的實現
實現重載 (1) 並保留 C++11 兼容性。
template<class ForwardIt, class UnaryPred>
ForwardIt partition(ForwardIt first, ForwardIt last, UnaryPred p)
{
first = std::find_if_not(first, last, p);
if (first == last)
return first;
for (auto i = std::next(first); i != last; ++i)
{
if (p(*i))
{
std::iter_swap(i, first);
++first;
}
}
return first;
}
|
示例
運行此代碼
#include <algorithm>
#include <forward_list>
#include <iostream>
#include <iterator>
#include <vector>
template <class ForwardIt>
void quicksort(ForwardIt first, ForwardIt last)
{
if (first == last)
return;
auto pivot = *std::next(first, std::distance(first, last) / 2);
auto middle1 = std::partition(first, last, [pivot](const auto& em)
{
return em < pivot;
});
auto middle2 = std::partition(middle1, last, [pivot](const auto& em)
{
return !(pivot < em);
});
quicksort(first, middle1);
quicksort(middle2, last);
}
int main()
{
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::cout << "原来的 vector:\n ";
for (int elem : v)
std::cout << elem << ' ';
auto it = std::partition(v.begin(), v.end(), [](int i) {return i % 2 == 0;});
std::cout << "\n划分后的 vector:\n ";
std::copy(std::begin(v), it, std::ostream_iterator<int>(std::cout, " "));
std::cout << "* ";
std::copy(it, std::end(v), std::ostream_iterator<int>(std::cout, " "));
std::forward_list<int> fl = {1, 30, -4, 3, 5, -4, 1, 6, -8, 2, -5, 64, 1, 92};
std::cout << "\n未排序的列表:\n ";
for (int n : fl)
std::cout << n << ' ';
quicksort(std::begin(fl), std::end(fl));
std::cout << "\n用 quicksort 排序后:\n ";
for (int fi : fl)
std::cout << fi << ' ';
std::cout << '\n';
}
可能的輸出:
原来的 vector:
0 1 2 3 4 5 6 7 8 9
划分后的 vector:
0 8 2 6 4 * 5 3 7 1 9
未排序的列表:
1 30 -4 3 5 -4 1 6 -8 2 -5 64 1 92
快速排序后:
-8 -5 -4 -4 1 1 1 2 3 5 6 30 64 92
缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
| 缺陷報告 | 應用於 | 出版時的行為 | 正確行為 |
|---|---|---|---|
| LWG 498 | C++98 | std::partition 要求 first 和 last 是老式雙向迭代器 (LegacyBidirectionalIterator) |
只需要是 老式向前迭代器 (LegacyForwardIterator) |
| LWG 2150 | C++98 | std::partition 只需要將一個滿足 p的元素放在一個不滿足 p 的元素之前
|
改正要求 |
參閱
(C++11) |
判斷範圍是否已按給定謂詞劃分 (函數模板) |
| 將元素分為兩組,同時保留其相對順序 (函數模板) | |
(C++20) |
將範圍中元素分為兩組 (算法函數對象) |