C++ STL数值操作函数说明

来源:互联网 发布:车辆工程专业排名知乎 编辑:程序博客网 时间:2024/06/16 11:56

STL中<algorithm>在最新的标准C++11下一共有85个算法,<numeric>中的数值操作函数,有5个,缺省版本的功能都是函数名的自解释。

1、accumulate()   累积
sum (1)

template <class InputIterator, class T>   T accumulate (InputIterator first, InputIterator last, T init);
custom (2)
template <class InputIterator, class T, class BinaryOperation>   T accumulate (InputIterator first, InputIterator last, T init,                 BinaryOperation binary_op);
用户定制的版本中,若容易中的元素按为a1,a2,a3....,an

那么输出的迭代计算这样进行:初始值作为二元函数的第一个参数传入,容器中的元素依次作为第二个参数,以后每次的计算结果作为下一次的第一个参数传入: x1=binary_op(init, a1);   x2 = binary_op(x1, a2)....   迭代,计算到 xn = binary_op(xn-1, an); xn 就是最终函数的返回值。

缺省二元函数是求和。

2、adjacent_difference()  相邻差

difference (1)

template <class InputIterator, class OutputIterator>   OutputIterator adjacent_difference (InputIterator first, InputIterator last,                                       OutputIterator result);
custom (2)
template <class InputIterator, class OutputIterator, class BinaryOperation>   OutputIterator adjacent_difference ( InputIterator first, InputIterator last,                                        OutputIterator result, BinaryOperation binary_op );
用户版本中,当前位置值作为二元函数的第一个参数,前一个位置的元素作为第二个参数。也就是输出为 a1, binary_op(a2, a1), binary_op(a3, a2)...  binary_op(an, an-1)

缺省二元函数是求差

3、partial_sum() 部分和

sum (1)

template <class InputIterator, class OutputIterator>   OutputIterator partial_sum (InputIterator first, InputIterator last,                               OutputIterator result);
custom (2)
template <class InputIterator, class OutputIterator, class BinaryOperation>   OutputIterator partial_sum (InputIterator first, InputIterator last,                               OutputIterator result, BinaryOperation binary_op);
用户定制版本中,输出为a1,  binary_op(a1, a2),  binary_op(binary_op(a1, a2), a3)   ..... 如此嵌套迭代。

缺省二元函数是求和。

4、iota() 

template <class ForwardIterator, class T>  void iota (ForwardIterator first, ForwardIterator last, T val);
将容器中的值填充为val起始的步长为1的连续数。

5、inner_product() 内积

sum/multiply (1)

template <class InputIterator1, class InputIterator2, class T>   T inner_product (InputIterator1 first1, InputIterator1 last1,                    InputIterator2 first2, T init);
custom (2)
template <class InputIterator1, class InputIterator2, class T,          class BinaryOperation1, class BinaryOperation2>   T inner_product (InputIterator1 first1, InputIterator1 last1,                    InputIterator2 first2, T init,                    BinaryOperation1 binary_op1,                    BinaryOperation2 binary_op2);

用户定制版本中,涉及两个区间都参与运算。

x1 = binary_op2(a1, b1) ,  然后计算 y1 = binary_op1(init, x1),   开始迭代:

x2 = binary_op2(a2, b2)    , y 2 = binary_op1(y1, x2),

x3 = binary_op2(a3, b3)  ,   y3 = binary_op1(y2, x3) .....

xn = binary_op2(an, bn),     yn = binary_op1(yn-1, xn).   最终将yn 返回。

缺省的binary_op1()是求和  , binary_op2() 都是作乘积。


0 0
原创粉丝点击