File: counting_iterator.cu

package info (click to toggle)
cccl 2.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 39,248 kB
  • sloc: cpp: 264,457; python: 6,421; sh: 2,762; perl: 460; makefile: 114; xml: 13
file content (42 lines) | stat: -rw-r--r-- 1,198 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <thrust/copy.h>
#include <thrust/device_vector.h>
#include <thrust/functional.h>
#include <thrust/iterator/counting_iterator.h>

#include <iostream>
#include <iterator>

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);

  // counting iterators define a sequence [0, 8)
  thrust::counting_iterator<int> first(0);
  thrust::counting_iterator<int> last = first + 8;

  // compute indices of nonzero elements
  typedef thrust::device_vector<int>::iterator IndexIterator;

  IndexIterator indices_end = thrust::copy_if(first, last, stencil.begin(), indices.begin(), thrust::identity<int>());
  // indices now contains [1,2,5,7]

  // print result
  std::cout << "found " << (indices_end - indices.begin()) << " nonzero values at indices:\n";
  thrust::copy(indices.begin(), indices_end, std::ostream_iterator<int>(std::cout, "\n"));

  return 0;
}