This first example creates a constant_iterator of type int with the value 10.
#include <thrust/iterator/constant_iterator.h>
thrust::constant_iterator<int> iter(10);
*iter; // returns 10
iter[0]; // returns 10
iter[1]; // returns 10
iter[13]; // returns 10
As you can see, iter mimics an infinite sequence of integers all with the value 10. While this behavior isn't all that exciting, it can be useful in practice. In the next example, we'll combine constant_iterator with transform to increment all elements in a sequence by a constant value.
#include <thrust/iterator/constant_iterator.h>
#include <thrust/transform.h>
#include <thrust/functional.h>
#include <thrust/device_vector.h>
int main(void)
{
thrust::device_vector<int> data(4);
data[0] = 3;
data[1] = 7;
data[2] = 2;
data[3] = 5;
// add 10 to all values in data
thrust::transform(data.begin(), data.end(),
thrust::constant_iterator<int>(10),
data.begin(),
thrust::plus<int>());
// data is now [13, 17, 12, 15]
return 0;
}
Note that we could have accomplished the same result by creating a temporary array and filling it with a constant value. However, this approach would have needlessly wasted
- memory capacity - by storing the values explicitly in memory
- memory bandwidth - by transferring values to and from memory
0 comments:
Post a Comment