了解Thrust中的二元谓词

时间:2012-12-21 12:10:14

标签: c++ c thrust

在回复我之前的question时,有人给了我以下代码:

thrust::device_vector<bool> bools;
thrust::device_vector<float> values;

typedef thrust::device_vector<bool>::iterator   BoolIterator;
typedef thrust::device_vector<float>::iterator  ValueIterator;
typedef thrust::tuple<BoolIterator, ValueIterator> IteratorTuple;
typedef thrust::zip_iterator<IteratorTuple> ZipIterator;

ZipIterator iter_begin(thrust::make_tuple(bools.begin(), values.begin()));
ZipIterator iter_end(thrust::make_tuple(bools.end(), values.end()));

struct Predicate
{
  __host__ __device__ bool operator () 
                      (const IteratorTuple& lhs, const IteratorTuple& lhs) 
  {
    if (get<0>(lhs) && get<0>(rhs) ) return get<1>(lhs) <= get<1>(rhs); else
    return ! get<0>(lhs) ;
  }
};

ZipIterator result =  thrust::max_element(iter_begin, iter_end, Predicate()); 

我想了解Predicate结构。如果运算符返回false会发生什么?选择哪个值?如果operator返回true会发生什么?选择了哪个值?

1 个答案:

答案 0 :(得分:1)

我试图实现'小于'谓词。如果lhs&lt; = rhs则返回true,否则返回false。另外,您请求通过存储在第二个数组中的布尔标志来排除值,因此它会检查它。

来自我的评论:

我想我过度优化了代码。这是“不到”的谓词。 if条件评估false表示一个或bool标志为false,因此我们需要排除相应的值。所以我们检查lhs参数是否应该被排除(thrust::get<0>(lhs) == false),如果是真的,谓词返回true,意思是'lhs小于rhs'。如果(thrust::get<0>(lhs) == true),则应排除rhs组件并且谓词返回false,表示'lhs不小于rhs'

我折叠了以下代码:

using thrust::get;
if (get<0>(lhs) && get<0>(rhs) ) return get<1>(lhs) <= get<1>(rhs); else 
// we need co check which value should be excluded from the seach
if (get<0>(lhs) == false) // lhs should be excluded so lhs is lesser
                          // OR both should be excluded and no matter what 
                          // we will return it will be eliminated in other comparison
  return true; else
if (get<0>(rhs) == false) // rhs should be excluded so rhs is lesser
  return false;
相关问题