initializing an array from iterators

M

Marc

Hello,

I want to initialize a std::array<Type,dim> from an iterator. I can do:
std::array<T,d> a={{iter[0],iter[1],...}};
and with index manipulations it even works if d is known at compile time
but not at code writing time.
If the iterator is not random access but only forward, I can replace
iter with next(iter,i), but that gives a quadratic number of ++,
which is wrong. Besides, it should be possible to use a pure input
iterator.

While I am describing the situation, let me mention that I dont want to
do:
T t=*iter;
array a={{t,...}};
because then t is copied/moved to the array instead of being constructed
directly into it (this iterator does some computations and returns a
temporary ripe for copy elision).

The best solution I can think of is to use a tuple-like class of
iterators where the constructor from iter initializes the first element
with *iter and the rest with ++iter (recursively, assuming tuple is
implemented like pair<head,tail>). I can then get the array by
dereferencing them all. The drawbacks are that std::tuple doesn't
provide this interface (the closest is cat_tuple, but I don't think it
would do), and that I can never remember if this is a case where the
order of evaluation is imposed or not:
Tuple(Iter i):head(*i),tail(++i){}
(I believe it is, but if not I am not sure how to make it work for an
input iterator).
 
M

Marc

Marc said:
The best solution I can think of is to use a tuple-like class of
iterators where the constructor from iter initializes the first element
with *iter and the rest with ++iter (recursively, assuming tuple is
implemented like pair<head,tail>). I can then get the array by
dereferencing them all. The drawbacks are that std::tuple doesn't
provide this interface (the closest is cat_tuple, but I don't think it
would do), and that I can never remember if this is a case where the
order of evaluation is imposed or not:
Tuple(Iter i):head(*i),tail(++i){}
(I believe it is, but if not I am not sure how to make it work for an
input iterator).

Hmm, I mixed two potential solutions in there, and I am getting
something that isn't a solution :-(
What the text describes corresponds to removing '*' from the previous
paragraph. But then it only works for forward iterators. With *, it
shows how to create a Tuple<T...>, but I want an array instead because
tuple doesn't have a constant time operator[].
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top