C++ STL adjacent_difference

本文详细介绍了C++标准库中的相邻差值算法`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 );

adjacent_difference : 对于给定的序列x0,x1,...,x(n-1),计算序列中相邻两个元素的差序列x1-x0,x2-x1,...,x(n-1)-x(n-2)。该算法可以把结果序列保存在原序列中,也可以保存在另一个区间中。

1:除了比较出差值,还可以作给定的交互。

2:第一个元素是不变的放入结果中的。

3:adjacent_difference() 是数值算法,使用 <numeric> 头文件。



#include "algostuff.hpp"
#include <iterator>
#include <ostream>
#include <numeric>


using namespace std;


int main(){
deque<int> coll;
INSERT_ELEMENTS(coll,1,6);
PRINT_ELEMENTS(coll);
cout<<endl;


adjacent_difference(coll.begin(),coll.end(),ostream_iterator<int>(cout," "));
cout<<endl;


adjacent_difference(coll.begin(),coll.end(),ostream_iterator<int>(cout," "),plus<int>());
cout<<endl;


adjacent_difference(coll.begin(),coll.end(),ostream_iterator<int>(cout," "),multiplies<int>());
cout<<endl;


return 0;
}


编译后输出:

 1 2 3 4 5 6 
1 1 1 1 1 1 
1 3 5 7 9 11 
1 2 6 12 20 30 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值