Can ForwardIterator and OutputIterator in C++ standard algorithms be the same?
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.
Yes, this would work fine. You would overwrite your source for the same amount of answer elements.
For example,
int square(int x) { return x*x; }
std::transform(vec.begin(), vec.end(), vec.begin(), square);
Would square each number in vec in their place.
精彩评论