Since there is no index based parallel for algorithm in c++17, I'm wondering if ranges::view::iota
can be used in combination with std::for_each
to emulate that. That is:
using namespace std;
constexpr int N= 10'000'000;
ranges::iota_view indices(0,N);
vector<int> v(N);
for_each(execution::par_unseq,indices.begin(),indices.end(),[&](int i) { v[i]= i; });
iota_view
seems to provide random access for appropriate types ([range.iota.iterator]):
iota_view<I, Bound>::iterator::iterator_category
is defined as follows:(1.1) — If
I
modelsAdvanceable
, theniterator_category
israndom_access_iterator_tag
.(1.2) — Otherwise, if
I
modelsDecrementable
, theniterator_category
isbidirectional_iterator_tag
.(1.3) — Otherwise, if
I
modelsIncrementable
, theniterator_category
isforward_iterator_tag
.(1.4) — Otherwise,
iterator_category
isinput_iterator_tag
.
Is the above code correct? Is there any performance penalty in using iota_view
this way?
EDIT: I've made some tests with range-v3, cmcstl2, and Intel's PSTL.
Using range-v3, the above example fails to compile with GCC 8. The compiler complains about begin
and end
having different types:
deduced conflicting types for parameter ‘_ForwardIterator’ (‘ranges::v3::basic_iterator<ranges::v3::iota_view<int, int> >’ and ‘ranges::v3::default_sentinel’)
Using cmcstl2 the code compiles cleanly, but it doesn't run in parallel. It seems to me that it falls back to the sequential version, maybe because the forward iterators requirements are somehow not met (https://godbolt.org/z/yvr-M2).
There is a somewhat related PSTL issue (https://github.com/intel/parallelstl/issues/22).