Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 714
Maciej Piechotka Avatar asked Mar 15 '26 21:03

Maciej Piechotka


1 Answers

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.

like image 64
Konrad Rudolph Avatar answered Mar 18 '26 09:03

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!