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, absolutely, as long as the iterator allows read/write in the first place (for instance, you obviously cannot read from std::cout). A common pattern is to use transform to mutate a vector in-place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With