STL算法

来源:互联网 发布:必读书 知乎 编辑:程序博客网 时间:2024/06/06 01:22

1.简介:

为了处理容器内的元素,STL提供了一些标准算法,包括排序,查找,拷贝,重新排序,修改,数值运算。
算法非容器类的成员函数,而是一种搭配迭代器的全局函数。

一些基本操作:#include<iostream>#include<vector>#include<algorithm>using namespace std;int main(){    vector<int> coll = { 2,5,4,1,6,3 };    auto minpos = min_element(coll.cbegin(), coll.cend());    cout << "min:" << *minpos << endl;    auto maxpos = max_element(coll.cbegin(), coll.cend());    cout << "max:" << *maxpos << endl;    sort(coll.begin(), coll.end());    auto pos3 = find(coll.begin(), coll.end(), 3);    reverse(pos3, coll.end());    for (auto elem : coll)    {        cout << elem << ' ';    }    cout << endl;    system("pause");}

2.区间:

所有算法都是用来处理一或多个区间的元素。这样的区间可以涵盖容器内的所有元素。为了操作容器里的某个子集,我们需要将区间首尾当两个实参。

所有算法处理的都是半开区间—包括起始位置不包括末尾位置。

#include<iostream>#include<list>#include<algorithm>using namespace std;int main(){    list<int> coll;    for (int i = 20; i <= 40; i++)    {        coll.push_back(i);     }    auto pos3 = find(coll.begin(), coll.end(),3);    reverse(pos3, coll.end());    list<int>::iterator pos25, pos35;    pos25 = find(coll.begin(), coll.end(), 25);    pos35 = find(coll.begin(), coll.end(), 35);     cout << "max=" << *max_element(pos25,pos35);    cout << "max=" << *max_element(pos25, ++pos35);    cout << endl;    system("pause");}

3.多重区间:

有数个算法可以同时处理多重空间。通常你必须设定第一个空间的起点和终点,至于其他空间你必须设定起点即可,终点可由第一区间的数量推导出来。

#include<iostream>#include<list>#include<deque>#include<algorithm>#include<vector>using namespace std;int main(){    list<int> coll1;    coll1 = { 1,2,3,4,5,6,7,8,9 };    vector<int> coll2;    coll2.resize(coll1.size());//初始化coll2的空间。    copy(coll1.cbegin(), coll1.cend(), coll2.begin());    deque<int> coll3(coll1.size());    copy(coll1.cbegin(), coll1.cend(), coll3.begin());//调用copy算法将第一区间元素拷贝到目标区间。    cout << endl;    system("pause");}

4.安插型迭代器:

迭代器第一个目标是 insert iterator,他可以使算方法以安插方式而非覆写的方式运作。可以解决算法的目标空间不足的问题。

原创粉丝点击