-2

How can I get "address" of every Nth element of a vector without using "raw loop". std::copy_if seems to be a solution but I couldn't get the address of the element, I just could get the value.

zontragon
  • 780
  • 1
  • 9
  • 27
  • How do you want to "get the address"? Do you want to have a vector of the addresses? Call a function with each of the addresses? Have a function that produces each address? Have an input iterator that produces the addresses? – Yakk - Adam Nevraumont Feb 28 '19 at 18:33
  • Sounds like you want a [skipping iterator](https://stackoverflow.com/questions/5685983/skipping-iterator) – NathanOliver Feb 28 '19 at 18:35
  • vector of te addresses. I tried to std::transform but it returns all elements and I don't want to hold a counter and if statement in lambda. – zontragon Feb 28 '19 at 18:36
  • 2
    Vectors are stored in contiguous memory ranges. Therefore if you have the address of the 1st element `&v[0]`, you can simply calculate the m-times.n-th element as `&v[0] + m * n * sizeof` where `T` is the type of the vector elements. – Frank Puffer Feb 28 '19 at 18:42

1 Answers1

0

You can use a skipping iterator (also called strided iterator) with std::for_each (or similar algorithm). The standard library has no generic skipping iterators however.

In case you wish to implement a skipping iterator yourself, the idea is simple: Write a template that takes an iterator as an argument. This template is an iterator "adaptor". Delegate most of the iterator boilerplate to the adapted iterator, but implement a custom increment operator, which skips elements based on your criteria.

While iterator adaptors are reusable, and existing implementations are available, a simple loop can be much less work:

for(size_t i = 0; i < v.size(); i += N)
eerorika
  • 232,697
  • 12
  • 197
  • 326