std::accumulate 和 std::reduce 累加求和 | 您所在的位置:网站首页 › cumulate与accumulate的区别 › std::accumulate 和 std::reduce 累加求和 |
中文标准库std::accumulate 中文标准库std::reduce std::accumulateaccumulate定义在头文件numeric中,作用有两个: 累加求和(不仅可以求int,float等类型还可以求和string类型) 自定义类型数据的处理 函数原型: template T accumulate( InputIt first, InputIt last, T init ); template //_Reduce_op是一个回调函数 _Ty accumulate(const _InIt _First, const _InIt _Last, _Ty _Val, _Fn _Reduce_op) 参数:first, last:要求和的元素范围 init,_Val:和的初值 示例: #include #include #include #include struct Grade { std::string name; int grade; }; int main() { Grade subject[3] = { { "English", 8 }, { "Biology", 7 }, { "History", 9 }}; std::vector str{ "abc","def","xyz" }; std::map 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 it) {return a + it.second; }); //一定注意,lambda表达式的第二个参数是pair,因为map容器的元素类型为pair system("pause"); return 0; } std::reduce类似std::accumulate,但不依序求和 std::transform_reduce中文标准库std::transform_reduce |
CopyRight 2018-2019 实验室设备网 版权所有 |