STL算法

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,他可以使算方法以安插方式而非覆写的方式运作。可以解决算法的目标空间不足的问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值