九、STL算法-不变序列算法(find、count、min、for_each)

STL算法-不变序列算法(find、count、min、for_each)

一、STL算法简介

STL中的算法大致可以分为以下七类:

  1. 不变序列算法
  2. 变值算法
  3. 删除算法
  4. 变序算法
  5. 排序算法
  6. 有序区间算法
  7. 数值算法

大多重载的算法都是有两个版本的:
1. 用 “==” 判断元素是否相等, 或用 “<” 来比较大小
2. 多出一个类型参数 “Pred” 和函数形参 “Pred op” ;通过表达式 “op(x,y)” 的返回值: ture/false,判断x是否 “等于” y,或者x是否 “小于” y。

如下面的有两个版本的min_element:

iterator min_element(iterator first, iterator last);
iterator min_element(iterator first, iterator last, Pred op);

二、不变序列算法

该类算法不会修改算法所作用的容器或对象,适用于顺序容器和关联容器,时间复杂度都是O(n)。

九、STL算法-不变序列算法(find、count、min、for_each)_第1张图片

九、STL算法-不变序列算法(find、count、min、for_each)_第2张图片

九、STL算法-不变序列算法(find、count、min、for_each)_第3张图片

find,返回区间 [first,last) 中的迭代器 i ,使得 * i == val:

template<class InIt, class T>
InIt find(InIt first, InIt last, const T& val);

find_if,返回区间 [first,last) 中的迭代器 i, 使得 pr(*i) == true:

template<class InIt, class Pred>
InIt find_if(InIt first, InIt last, Pred pr);

for_each,对[first, last)中的每个元素e, 执行f(e), 要求 f(e)不能改变e:

template<class InIt, class Fun>
Fun for_each(InIt first, InIt last, Fun f);

count,计算[first, last) 中等于val的元素个数(x==y为true算等于):

template<class InIt, class T>
size_t count(InIt first, InIt last, const T& val);

count_if,计算[first, last) 中符合pr(e) == true 的元素e的个数:

template<class InIt, class Pred>
size_t count_if(InIt first, InIt last, Pred pr);

min_element,返回[first,last) 中最小元素的迭代器, 以 “<” 作比较器;最小指没有元素比它小,而不是它比别的不同元素都小,因为即便a!= b, a

template <class FwdIt>
FwdIt min_element(FwdIt first, FwdIt last);

max_element,返回[first,last) 中最大元素(不小于任何其他元素)的迭代器,以 “<” 作比较器

template<class FwdIt>
FwdIt max_element(FwdIt first, FwdIt last);

三、程序示例

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

class A
{
    public:
        int n;
        A(int a):n(a){ }
};

bool operator<(const A & a, const A & b)
{
    return a.n<b.n;
}

class LessThan5
{
    public:
        bool operator()(int n) { return n<5; }
}; 

class outputSqure
{
    public:
        void operator()(int n) { cout<<n*n<<endl; }
};

int main()
{
    A a[] = {5, 7, 8, 2, 4, 1, 6, 3, 9, 0};
    cout<<min_element(a, a+10)->n<<endl;
    cout<<max_element(a, a+10)->n<<endl;

    cout<<"*********"<<endl;

    int b[] = {5, 7, 8, 2, 4, 1, 6, 3, 9, 0};
    vector<int> v(b, b+10);
    vector<int>::iterator i;
    i = find(v.begin(), v.end(), 9);
    if(i!=v.end()){
        cout<<"9 found, at "<<i-v.begin()<<endl;
    }
    i = find_if(v.begin(), v.end(), LessThan5());
    if(i!=v.end()){
        cout<<"found, at "<<i-v.begin()<<endl;
    }

    cout<<"*********"<<endl;

    v.push_back(5);
    v.push_back(5);

    cout<<count(v.begin(), v.end(), 5)<<endl;;
    cout<<count_if(v.begin(), v.end(), LessThan5())<<endl;

    return 0;
} 

输出:

0
9
*********
9 found, at 8
found, at 3
*********
3
5

你可能感兴趣的:(算法,STL)