Key filter by key value

In my application, I have a class like this:

class sample{
    thrust::device_vector<int>   edge_ID;
    thrust::device_vector<float> weight;
    thrust::device_vector<int>   layer_ID;

/*functions, zip_iterators etc. */

};

In this index, each vector stores the corresponding data for the same edge.

I want to write a function that filters out all the edges of a given layer, something like this:

void filter(const sample& src, sample& dest, const int& target_layer){
      for(...){
        if( src.layer_ID[x] == target_layer)/*copy values to dest*/;
      }
}

The best way I've found this is to use thrust::copy_if(...) (more)

It will look like this:

void filter(const sample& src, sample& dest, const int& target_layer){
     thrust::copy_if(src.begin(),
                     src.end(),
                     dest.begin(),
                     comparing_functor() );
}

And here we achieve our problem :

comparing_functor()is a unary function, which means that I cannot pass the value to me target_layer.

Does anyone know how to get around this, or have an idea to implement this while maintaining the integrity of the class data structure?

+2
source share
1 answer

, . :

#include <iostream>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>

#define DSIZE 10
#define FVAL 5

struct test_functor
{
  const int a;

  test_functor(int _a) : a(_a) {}

  __device__
  bool operator()(const int& x ) {
    return (x==a);
    }
};

int main(){
  int target_layer = FVAL;
  thrust::host_vector<int> h_vals(DSIZE);
  thrust::sequence(h_vals.begin(), h_vals.end());
  thrust::device_vector<int> d_vals = h_vals;
  thrust::device_vector<int> d_result(DSIZE);
  thrust::copy_if(d_vals.begin(), d_vals.end(), d_result.begin(),  test_functor(target_layer));
  thrust::host_vector<int> h_result = d_result;
  std::cout << "Data :" << std::endl;
  thrust::copy(h_vals.begin(), h_vals.end(), std::ostream_iterator<int>( std::cout, " "));
  std::cout << std::endl;
  std::cout << "Filter Value: " << target_layer << std::endl;
  std::cout << "Results :" << std::endl;
  thrust::copy(h_result.begin(), h_result.end(), std::ostream_iterator<int>( std::cout, " "));
  std::cout << std::endl;
  return 0;
}
+2

All Articles