# Thrust::transform with conditional

This is what my vector subtraction looks like now -

``````thrust::transform(d_arr2.begin(), d_arr2.end(), d_arr.begin(), data.begin(), thrust::minus<T>());
``````

For each d_arr[i] and d_arr2[i], I want to check

``````if d_arr2[i] <= d_arr[i]
Callfunction();
Don't transform;
``````

(Don’t transform is not super important)

How do I do this without increasing the complexity?

The first thing that came to mind is using thrust::transform_if but I am not sure how to fit a conditional with the function call into it. I would really appreciate any help!

Checkout the transformation section https://github.com/thrust/thrust/wiki/Quick-Start-Guide

Here is a simple solution. I bet there are others as well.

``````#include <thrust/transform.h>
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <vector>

__host__ __device__
void Callfunction(int & out, const int & a, const int & b ) {
out = a * b;
}

struct functor
{
const int scalar;

functor( int _scalar ) : scalar( _scalar ) {}

__host__ __device__
int operator()( const int& x, const int& y ) const
{
int temp { INT_MAX };
if (y < x) {
std::printf( "Call function\n" );
Callfunction( temp, y, scalar );
} else {
std::printf( "Don't transform\n" );
}

return ( temp );
}
};

int main (void) {

std::vector<int> h_arr  = { 3,  6,  2,  1,  2,  3};
std::vector<int> h_arr2 = {-5,  0, -2,  3,  2, -4};

thrust::device_vector<int> d_arr ( h_arr );
thrust::device_vector<int> d_arr2 ( h_arr2 );
thrust::device_vector<int> d_output ( h_arr.size() );

const int scalar { 4 };

thrust::transform( d_arr.begin(), d_arr.end(), d_arr2.begin(), d_output.begin(), functor( scalar ) );

thrust::host_vector<int> h_output ( d_output );

for ( int i = 0; i < 6; i++ )
std::printf( "%d\n", h_output[i] );

return ( EXIT_SUCCESS );
}
``````