Can the ‘streaming’ algorithm like std::transform or std::partial_sum read from and write to the same place?
For example the following code works in gcc but I’m not sure if it is not ‘just accident’ and compiler is free to break the code in order to optimize it.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main()
{
int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int> vec(arr, arr + sizeof(arr)/sizeof(arr[0]));
std::partial_sum(vec.begin(), vec.end(), vec.begin());
for(std::vector<int>::iterator iter = vec.begin(); iter != vec.end(); iter++)
std::cout << *iter << std::endl;
return 0;
}
Yes, this would work fine. You would overwrite your source for the same amount of answer elements.
For example,
Would square each number in vec in their place.