- partition 与 stable_partition 的详述
partition会将区间[first,last)中的元素重新排列,满足判断条件pred的元素会被放在区间的前段,不满足pred的元素会被放在区间的后段。该算法不能保证元素的初始相对位置,如果需要保证初始相对位置,应该使用stable_partition。
- 代码示例
bool IsOdd(int num) //判断奇数
{
return num & 1; //num & 1 ; 是一个bool值:若为1,则num为奇数;若为0,则num为偶数。
}
int main()
{
std::vector<int> ivec;
for (int i = 1; i < 20; ++i)
ivec.push_back(i); // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
auto bound1 = stable_partition(ivec.begin(), ivec.end(), IsOdd);
for (auto ite = ivec.begin(); ite != ivec.end(); ++ite)
{
cout << *ite << " ";
}
cout << endl;
cout << endl;
auto bound = partition(ivec.begin(), ivec.end(), IsOdd); //partition与stable_partition的位置不同,输出的结果的顺序也就不同
std::cout << "odd elements:";
for (auto it = ivec.begin(); it != bound; ++it)
cout << ' ' << *it;
cout << endl;
cout << "even elements:";
for (auto it = bound; it != ivec.end(); ++it)
cout << ' ' << *it;
cout << endl;
system("pause");
return 0;
}
注:若想要看到不一样的输出结果,可调整bound与bound1对应行的代码位置!