thrust::offset_iterator

Defined in thrust/iterator/offset_iterator.h

template<typename Iterator, typename Offset = typename ::cuda::std::iterator_traits<Iterator>::difference_type>
class offset_iterator : public thrust::iterator_adaptor<offset_iterator<Iterator, typename ::cuda::std::iterator_traits<Iterator>::difference_type>, Iterator>

offset_iterator wraps another iterator and an integral offset, applies the offset to the iterator when dereferencing, comparing, or computing the distance between two offset_iterators. This is useful, when the underlying iterator cannot be incremented, decremented, or advanced (e.g., because those operations are only supported in device code).

The following code snippet demonstrates how to create an offset_iterator:

#include <thrust/iterator/offset_iterator.h>
#include <thrust/fill.h>
#include <thrust/device_vector.h>

int main()
{
  thrust::device_vector<int> data{1, 2, 3, 4};
  auto b = offset_iterator{data.begin(), 1};
  auto e = offset_iterator{data.end(), -1};
  thrust::fill(b, e, 42);
  // data is now [1, 42, 42, 4]
  ++b; // does not call ++ on the underlying iterator
  assert(b == e - 1);

  return 0;
}

Alternatively, an offset_iterator can also use an iterator to retrieve the offset from an iterator. However, such an offset_iterator cannot be moved anymore by changing the offset, so it will move the base iterator instead.

#include <thrust/iterator/offset_iterator.h>
#include <thrust/fill.h>
#include <thrust/functional.h>
#include <thrust/device_vector.h>

int main()
{
  using thrust::placeholders::_1;
  thrust::device_vector<int> data{1, 2, 3, 4};

  thrust::device_vector<ptrdiff> offsets{1}; // offset is only available on device
  auto offset = thrust::make_transform_iterator(offsets.begin(), _1 * 2);
  thrust::offset_iterator iter(data.begin(), offset); // load and transform offset upon access
  // iter is at position 2 (= 1 * 2) in data, and would return 3 in device code

  return 0;
}

In the above example, the offset is loaded from a device vector, transformed by a transform_iterator, and then applied to the underlying iterator, when the offset_iterator is accessed.

Public Types

using base_type = Iterator

The type of iterator this iterator_adaptor's adapts.

Public Functions

inline Iterator const &base() const
Returns

A const reference to the Base iterator this iterator_adaptor adapts.

Protected Functions

inline Iterator const &base_reference() const
Returns

A const reference to the Base iterator this iterator_adaptor adapts.

inline Iterator &base_reference()
Returns

A mutable reference to the Base iterator this iterator_adaptor adapts.