1

Is there a better way of iterating over the indices of a container than doing something like this

for (auto i : view::iota(0, vec.size())

Ideally something that would look just like this view::something(vec).

I understand I can write my own function to do this, but was wondering if this functionality already existed. I am also aware of being able to do something like this

for (auto [idx, elm] : view::zip(view::indices, vec))

After some code examination, I have become aware of being able to write this instead view::indices(vec.size()), however even though indices has ptrdiff_t as a default, using size() results in it producing size_t, and I would rather retain the ptrdiff_t.

user975989
  • 2,578
  • 1
  • 20
  • 38

1 Answers1

0

If you need only the indices, then your first is fine.

There also is the older (but no less good)

for (auto i = 0; i < vec.size(); ++i)

If you also need the elements, then your second is superior.

Caleth
  • 52,200
  • 2
  • 44
  • 75
  • Warning may occur in the comparison of `int i` and `std::vector::size`. One way to avoid it is `auto i = 0U` ? https://wandbox.org/permlink/WGZe8zUolxmYxRr9 – Hiroki Oct 12 '18 at 14:05
  • Part of the motivation for this question is to pipe into other `view`s and also to move the need for a signed-unsigned cast elsewhere. – user975989 Oct 13 '18 at 02:28
  • @Hiroki, `auto i = 0U` isn't good enough. `vector<>::size_type` is 8 bytes in x64, `0U` is 4 bytes. It's possible the loop never ends. Here's proposal to add `size_t` and `ptrdiff_t` literal to C++ standard, so we can write `auto i = 0zu`. http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/p0330r0.pdf – MaxPlankton Oct 30 '18 at 05:44