cpp/algorithm/adjacent difference:修订间差异
来自cppreference.com
小 1个修订: Translate from the English version |
小 r2.7.3) (机器人添加:de, en, es, fr, it, pt 去除:zh |
||
| 第120行: | 第120行: | ||
{{dcl list end}} | {{dcl list end}} | ||
[[ja:cpp/algorithm/adjacent difference]] | [[ja:cpp/algorithm/adjacent difference]] | ||
[[ru:cpp/algorithm/adjacent difference]] | [[ru:cpp/algorithm/adjacent difference]] | ||
2012年11月3日 (六) 03:07的版本
|
|
该页由英文版维基使用谷歌翻译机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击此处。 |
<metanoindex/>
| 在标头 <numeric> 定义
|
||
| |
(1) | |
| |
(2) | |
计算所述第二和第一元素的范围内
[first, last)的每个相邻对之间的差异,并且将它们写入到的范围内开始,d_first + 1。未修改的副本,first被写入d_first。第一个版本使用operator-来计算的差异,第二个版本使用给定的二进制功能的op.原文:
Computes the differences between the second and the first of each adjacent pair of elements of the range
[first, last) and writes them to the range beginning at d_first + 1. Unmodified copy of first is written to d_first. The first version uses operator- to calculate the differences, the second version uses the given binary function op.*(d_first) = *first;
*(d_first+1) = (*first+1) - *(first);
*(d_first+2) = (*first+2) - *(first+1);
*(d_first+3) = (*first+3) - *(first+2);
...
参数
Template:param list begin Template:param list item Template:param list item Template:param list op2 Template:param list hreq Template:param list req concept Template:param list req concept Template:param list end
返回值
它过去的最后一个元素的元素写的
复杂性
究竟
(last - first) - 1应用程序的二进制运算可能的实现
| 版本一 |
|---|
template<class InputIt, class OutputIt>
OutputIt adjacent_difference(InputIt first, InputIt last,
OutputIt d_first)
{
if (first == last) return d_first;
typedef typename std::iterator_traits<InputIt>::value_type value_t;
value_t acc = *first;
*d_first = acc;
while (++first != last) {
value_t val = *first;
*++d_first = val - acc;
acc = std::move(val);
}
return ++d_first;
}
|
| 版本二 |
template<class InputIt, class T, class BinaryOperation>
OutputIt adjacent_difference(InputIt first, InputIt last,
OutputIt d_first, BinaryOperation op)
{
if (first == last) return d_first;
typedef typename std::iterator_traits<InputIt>::value_type value_t;
value_t acc = *first;
*d_first = acc;
while (++first != last) {
value_t val = *first;
*++d_first = op(val, acc);
acc = std::move(val);
}
return ++d_first;
}
|
为例
下面的代码转换为偶数序列的重复数2与斐波那契数列的序列的序列转换.
运行此代码
#include <numeric>
#include <vector>
#include <iostream>
#include <functional>
int main()
{
std::vector<int> v{2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
std::adjacent_difference(v.begin(), v.end(), v.begin());
for(auto n: v) {
std::cout << n << ' ';
}
std::cout << '\n';
v = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
std::adjacent_difference(v.begin(), v.end()-1, v.begin()+1, std::plus<int>()
for(auto n: v) {
std::cout << n << ' ';
}
std::cout << '\n';
}
输出:
2 2 2 2 2 2 2 2 2 2
1 1 2 3 5 8 13 21 34 55