dimanche 24 février 2019

Iterating over an odd elements only in a range-based loop

Suppose we have an array (or other container which support range based loops)

const int N = 8;
int arr[N] = {0, 1, 2, 3, 4, 5, 6, 7};

Using indexes or iterators we can loop over odd elements increasing the index by two:

for (int i = 0; i < N; i+=2)
{
   std::cout << arr[i] << std::endl;
}

How can I get a similar result using range based loop and avoiding explicit iterators/indexes or iteration skipping usage? Something like:

for (const auto& v: odd_only(arr))
{
   std::cout << v << std::endl;
}

What the simple and elegant solution do you see? Does stl contain something like that?

Aucun commentaire:

Enregistrer un commentaire