std::accumulate 和 std::reduce 累加求和

中文标准库std::accumulate

中文标准库std::reduce

std::accumulate

accumulate定义在头文件numeric中,作用有两个:

  • 累加求和(不仅可以求int,float等类型还可以求和string类型)

  • 自定义类型数据的处理

函数原型:

template <class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

template <class _InIt, class _Ty, class _Fn>  //_Reduce_op是一个回调函数
_Ty accumulate(const _InIt _First, const _InIt _Last, _Ty _Val, _Fn _Reduce_op)

参数:

  • first, last:要求和的元素范围

  • init,_Val:和的初值

示例:

#include <string>
#include <vector>
#include <numeric>
#include <map>

struct Grade
{
    std::string name;
    int grade;
};

int main()
{
    Grade subject[3] = {
        { "English", 8 },
        { "Biology", 7 },
        { "History", 9 }};

    std::vector<std::string> str{ "abc","def","xyz" };
    std::map<std::string, int> m{ {"a",2},{"b",3},{"c",4} };

    //auto r = std::accumulate(std::begin(str), std::end(str), "");  //报错,第三个参数类型必须保持一致
    //sum0 = "abcdefxyz"
    auto sum0 = std::accumulate(std::begin(str), std::end(str), std::string(""));
    //sum1 = 24  sum2 = 9
    int sum1 = std::accumulate(subject, subject + 3, 0, [](int a, Grade b) {return a + b.grade; });
    int sum2 = std::accumulate(m.begin(),m.end(), 0, [](int a, std::pair<std::string, int> it) {return a + it.second; });
    //一定注意,lambda表达式的第二个参数是pair,因为map容器的元素类型为pair
    system("pause");
    return 0;
}

std::reduce

类似std::accumulate,但不依序求和

std::transform_reduce

中文标准库std::transform_reduce

原文地址:https://www.cnblogs.com/mmmmmmmmm/p/14024639.html