您的位置:首页 > 其它

STL学习记录(十四):其它几种算法

2015-07-31 21:27 381 查看

其它几种算法Paritition、Heap、Min/Max

在介绍前面几种算法后,剩下的几种算法将在这一部分集中介绍。Partition算法主要是根据定义的规则,将范围内的元素分为两部分。

Heap算法主要是关于堆部分的算法。而Min/Max类算法主要是关于数值部分的算法。算法说明与示例如下:

操作说明
partition(beg,end,op)根据op操作将[beg,end)分为两部分,返回值为false部分首位置或者last
stable_partiton(beg,end,op)根据op进行稳定的类别区分
is_partition(beg,end,op)判断[beg,end)是否根据op操作分为了两个部分
partition_copy(beg,end,desT,desF,op)根据op操作将[beg,end)分别拷贝到dest、desF
partition_point(beg,end,op)返回划分后第一个false元素的位置
操作说明
push_heap(beg,end)将end-1所指元素添加到已有堆[beg,end-1)中并建立新堆(可自定义规则)
pop_heap(beg,end)交换第一个元素到end-1,并对[beg,end-1)重新建堆
make_heap(beg,end)对[beg,end)元素进行建堆操作
sort_heap(beg,end)对[beg,end)堆进行排序(可自定义排序规则)
is_heap(beg,end)判断[beg,end)是否为堆
is_heap_until(beg,end)返回第一个不符合建堆的元素位置(可自定义建堆规则)
操作说明
min(a,b)返回a,b两者中的较小者,相等则返回a
max(a,b)返回两者中的较大者,相等返回a
minmax(a,b)将a、b比较结果以pair(min,max)返回,相等返回pair(a,b)
min_element(beg,end)返回[beg,end)中最小的元素的位置,若都相等返回first
max_element(beg,end)返回[beg,end)中最大的元素的位置,若都相等返回first
minmax_element(beg,end)将[beg,end)中最小,最大的元素的位置以pair(min_pos,max_pos)返回
代码示例:

// partition algorithm example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

bool IsOdd(int i) { return (i % 2) == 1; }

int main() {

vector<int> myvector{ 1, 2 ,3 ,4, 5 ,6 ,7 ,8 ,9 };

vector<int>::iterator bound;

bound = partition(myvector.begin(), myvector.end(), IsOdd);

// print out content:
cout << "odd elements: ";
for (vector<int>::iterator it = myvector.begin(); it != bound; ++it)
cout << *it << ' ';
cout << endl;

cout << "even elements: ";
for (vector<int>::iterator it = bound; it != myvector.end(); ++it)
cout << *it << ' ';
cout << endl;

return 0;
}

//output:
//odd elements: 1 9 3 7 5
//even elements: 6 4 8 2


// range heap example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main () {

vector<int> v{10,20,30,5,15};;

make_heap (v.begin(),v.end());
cout << "initial max heap   : " << v.front() << '\n';

pop_heap (v.begin(),v.end()); v.pop_back();
cout << "max heap after pop : " << v.front() << '\n';

v.push_back(99);   push_heap (v.begin(),v.end());
cout << "max heap after push: " << v.front() << '\n';

sort_heap (v.begin(),v.end());

cout << "final sorted range :";
for (unsigned i=0; i<v.size(); i++)
cout << ' ' << v[i];

cout << '\n';

return 0;
}

//output:
//initial max heap   : 30
//max heap after pop : 20
//max heap after push: 99
//final sorted range : 5 10 15 20 99


// minmax example
#include <iostream>
#include <algorithm>
using namespace std;

int main () {
auto result = minmax({1,2,3,4,5});

cout << "minmax({1,2,3,4,5}): ";
cout << result.first << ' ' << result.second << '\n';
return 0;
}

//output:
//minmax({1,2,3,4,5}): 1 5
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: