stable_partition()算法排列由開始和結束定義的序列,以使由pfn指定的謂詞返回true的所有元素都位於該謂詞返回false的元素之前。分區是穩定的。這意味著保留了序列的相對順序。句法:
template BiIter stable_partition(BiIter start, BiIter end, UnPred pfn);
參數:
start: the range of elements to reorder end: the range of elements to reorder pfn: User-defined predicate function object that defines the condition to be satisfied if an element is to be classified. A predicate takes single argument and returns true or false. 返回值: Returns an iterator to the beginning of the elements for which the predicate is false.
該函數嘗試分配一個臨時緩衝區。如果分配失敗,則選擇效率較低的算法。
範例1:
// CPP program to illustrate stable_partition
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> v{ 6, 9, 0, 1, 2, 7, 5, 8, 0 };
stable_partition(v.begin(), v.end(), [](int n) {return n>0; });
for (int n:v) {
cout << n << ' ';
}
cout << '\n';
}
輸出:
6 9 1 2 7 5 8 0 0
範例2:
// CPP program to illustrate stable_partition
#include <iostream>
#include <algorithm> // std::stable_partition
#include <vector>
bool odd(int i) { return (i % 2) == 1; }
int main()
{
std::vector<int> vct;
for (int i = 1; i < 10; ++i)
vct.push_back(i); // 1 2 3 4 5 6 7 8 9
std::vector<int>::iterator bound;
bound = std::stable_partition(vct.begin(), vct.end(), odd);
std::cout << "odd numbers:";
for (std::vector<int>::iterator it = vct.begin(); it != bound; ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "evennumbers:";
for (std::vector<int>::iterator it = bound; it != vct.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
輸出:
odd numbers:1 3 5 7 9 even numbers:2 4 6 8
範例3:
// CPP program to illustrate stable_partition
#include <algorithm>
#include <deque>
#include <functional>
#include <iostream>
#include <iterator>
template <class Arg>
struct is_even:public std::unary_function<Arg, bool> {
bool operator()(const Arg& arg1) const
{
return (arg1 % 2) == 0;
}
};
int main()
{
typedef std::deque<int, std::allocator<int> > Deque;
typedef std::ostream_iterator<int, char,
std::char_traits<char> >
Iter;
const Deque::value_type a[] = { 1, 2, 3, 4, 5,
6, 7, 8, 9, 10 };
Deque d1(a + 0, a + sizeof a / sizeof *a);
Deque d2(d1);
std::cout << "Unpartitioned values:\t\t";
std::copy(d1.begin(), d1.end(), Iter(std::cout, " "));
std::partition(d2.begin(), d2.end(), is_even<int>());
std::cout << "\nPartitioned values:\t\t";
std::copy(d2.begin(), d2.end(), Iter(std::cout, " "));
std::stable_partition(d1.begin(), d1.end(),
is_even<int>());
std::cout << "\nStable partitioned values:\t";
std::copy(d1.begin(), d1.end(), Iter(std::cout, " "));
std::cout << std::endl;
return 0;
}
輸出:
Unpartitioned values: 1 2 3 4 5 6 7 8 9 10 Partitioned values: 10 2 8 4 6 5 7 3 9 1 Stable partitioned values: 2 4 6 8 10 1 3 5 7 9
複雜度:謂詞的end-start確實是應用程序,如果內存不足,則最多(end-start)* log(end-start)交換;如果有足夠的內存,則線性交換數。
相關用法
注:本文由純淨天空篩選整理自 std::stable_partition in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。