Using functors in Thrust

Let's see how we can use a concept known as functors in Thrust. In C++, a functor is a class or struct object that looks and acts like a function; this lets us use something that looks and acts like a function, but can hold some parameters that don't have to be set every time it is used.

Let's start a new Thrust program with the appropriate include statements, and use the standard namespace:

#include <thrust/host_vector.h>#include <thrust/device_vector.h>#include <iostream>using namespace std;

Now, let's set up a basic functor. We will use a struct to represent this, rather than class. This will be a weighted multiplication function, and we will store the weight in a float called w. We will make a constructor that ...

Get Hands-On GPU Programming with Python and CUDA now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.