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

STL:通用数值计算

程序员文章站 2022-03-23 10:52:30
...

STL:通用数值计算

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

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

void print(int elem)
{
    cout << elem << " ";
}

int defop(int ori, int elem)
{
    return ori * 2 + elem;
}

int defop2(int initv, int elem)
{
    return initv + elem;
}

int main()
{
    vector<int> vec = {1, 2, 3, 4, 5};
    vector<int> vec2 = {3, 4, 5, 6, 7};

/*求和*/

    int accval;
    accval = accumulate(vec.begin(), vec.end(), 0);
    printf("sccval:%d\n", accval);
    accval = accumulate(vec.begin(), vec.end(), 0, defop);
    printf("accval:%d\n", accval);

/*内积*/

    int inprodval;
    inprodval = inner_product(vec.begin(), vec.end(), vec2.begin(), 0);
    printf("inprodval:%d\n", inprodval);
    inprodval = inner_product(vec.begin(), vec.end(), vec2.begin(), 0, defop2, defop);
    printf("inprodval:%d\n", inprodval);

    //等价于
    inprodval = 0;
    for(int i = 0; i < vec.size(); i++)
    {
        inprodval += vec[i] * 2 + vec2[i];
    }
    printf("inprodval:%d\n", inprodval);

/*部分和*/

    vector<int> vec3, vec4;
    partial_sum(vec.begin(), vec.end(), back_inserter(vec3));
    for_each(vec3.begin(), vec3.end(), print);      //1 3 6 10 15
    cout << endl;
    partial_sum(vec.begin(), vec.end(), back_inserter(vec4), defop);
    for_each(vec4.begin(), vec4.end(), print);      //1 4 11 26 57
    cout << endl;

/*序列相邻差*/

    vector<int> vec5, vec6;
    adjacent_difference(vec.begin(), vec.end(), back_inserter(vec5));
    for_each(vec5.begin(), vec5.end(), print);      //1 1 1 1 1
    cout << endl;
    adjacent_difference(vec.begin(), vec.end(), back_inserter(vec6), defop);
    for_each(vec6.begin(), vec6.end(), print);      //1 5 8 11 14
    cout << endl;

    return 0;
}