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中都有提到會生成臨時變量存儲前一個元素以備下一次使用,看來我們可以放心用了。