欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

STL:算法

程序员文章站 2022-07-12 17:59:18
...

STL:算法

参考文献《大道至简:C++STL》

  • for_each()、count()、min_element()/max_element()
#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <algorithm>

#ifndef __print__
    #define __print__(x) {std::cout << x << " ";}
#endif

#ifndef newline
    #define newline() {std::cout << std::endl;}
#endif

using namespace std;

template <typename T> void _pow(T& t) {t *= t;}

template <typename T> void print(const T& t){__print__(t);}

class SUM
{
private:
    long total;
public:
    SUM():total(0){}
    void operator()(int val)
    {
        total += val;
    }
    operator double()
    {
        return static_cast<double>(total);
    }
};

bool is_even(const int& x){return x % 2 == 0;}
template <typename T> bool abs_val(const T& t1, const T& t2){return abs(t1) < abs(t2);};

int main()
{

/*for_each()*/

    vector<int> vint = {1, 3, 5, 7};
    for_each(vint.begin(), vint.end(), print<int>);
    newline();
    for_each(vint.begin(), vint.end(), _pow<int>);
    for_each(vint.begin(), vint.end(), print<int>);
    newline();
    double sum = for_each(vint.begin(), vint.end(), SUM());
    print(sum);
    newline();

/*count()*/

    deque<int> dint = {2, 5, 4, 1, 8, 3, 6};
    for_each(dint.begin(), dint.end(), print<int>);
    newline();
    print(count(dint.begin(), dint.end(), 4));
    print(count_if(dint.begin(), dint.end(), bind2nd(greater<int>(), 3)));
    print(count_if(dint.begin(), dint.end(), is_even));
    newline();

/*min_element/max_element*/

    list<int> lint = {-1, 4, 6, -12, 9};
    print(*min_element(lint.begin(), lint.end()));
    newline();
    print(*max_element(lint.begin(), lint.end()));
    newline();
    print(*min_element(lint.begin(), lint.end(), abs_val<int>));    //-1
    newline();
    print(*max_element(lint.begin(), lint.end(), abs_val<int>));    //-12
    newline();

    return 0;
}