thrust::counting_iterator
Defined in thrust/iterator/counting_iterator.h
-
template<typename Incrementable, typename System = use_default, typename Traversal = use_default, typename Difference = use_default>
class counting_iterator : public detail::counting_iterator_base::type<Incrementable, use_default, use_default, use_default> counting_iterator
is an iterator which represents a pointer into a range of sequentially changing values. This iterator is useful for creating a range filled with a sequence without explicitly storing it in memory. Usingcounting_iterator
saves memory capacity and bandwidth.The following code snippet demonstrates how to create a
counting_iterator
whosevalue_type
isint
and which sequentially increments by1
.#include <thrust/iterator/counting_iterator.h> ... // create iterators thrust::counting_iterator<int> first(10); thrust::counting_iterator<int> last = first + 3; first[0] // returns 10 first[1] // returns 11 first[100] // returns 110 // sum of [first, last) thrust::reduce(first, last); // returns 33 (i.e. 10 + 11 + 12) // initialize vector to [0,1,2,..] thrust::counting_iterator<int> iter(0); thrust::device_vector<int> vec(500); thrust::copy(iter, iter + vec.size(), vec.begin());
This next example demonstrates how to use a
counting_iterator
with thethrust::copy_if
function to compute the indices of the non-zero elements of adevice_vector
. In this example, we use themake_counting_iterator
function to avoid specifying the type of thecounting_iterator
.#include <thrust/iterator/counting_iterator.h> #include <thrust/copy.h> #include <thrust/functional.h> #include <thrust/device_vector.h> int main() { // this example computes indices for all the nonzero values in a sequence // sequence of zero and nonzero values thrust::device_vector<int> stencil(8); stencil[0] = 0; stencil[1] = 1; stencil[2] = 1; stencil[3] = 0; stencil[4] = 0; stencil[5] = 1; stencil[6] = 0; stencil[7] = 1; // storage for the nonzero indices thrust::device_vector<int> indices(8); // compute indices of nonzero elements using IndexIterator = thrust::device_vector<int>::iterator; // use make_counting_iterator to define the sequence [0, 8) IndexIterator indices_end = thrust::copy_if(thrust::make_counting_iterator(0), thrust::make_counting_iterator(8), stencil.begin(), indices.begin(), thrust::identity<int>()); // indices now contains [1,2,5,7] return 0; }
See also
make_counting_iterator