使用adjacent_difference要注意的小问题

时间:2023-03-09 16:26:31
使用adjacent_difference要注意的小问题

adjacent_difference的源与目的地可以相同,这是在标准中说明的,所以我产生了疑问,会不会因为这样使用而改变了当前成员,而影响下一步计算呢,经试验,在vs2015里并不会。

#include "stdafx.h"
#include "algostuff.hpp"
using namespace std; int main()
{
deque<int> coll; INSERT_ELEMENTS(coll, 1, 6);
PRINT_ELEMENTS(coll); // print all sums with the predecessors
adjacent_difference(coll.cbegin(), coll.cend(), // source
ostream_iterator<int>(cout, " "), // destination
plus<int>()); // operation
cout << endl; // print all sums with the predecessors to the source
adjacent_difference(coll.cbegin(), coll.cend(), // source
coll.begin(), // destination
plus<int>());
PRINT_ELEMENTS(coll);
cout << endl;
return 0;
}

输出:

1 2 3 4 5 6
1 3 5 7 9 11
1 3 5 7 9 11

看来并无影响。

在侯捷先生的STL源码剖析和cppreference中都有提到会生成临时变量存储前一个元素以备下一次使用,看来我们可以放心用了。