理解Thrust中的二元谓词

Understanding binary predicates in Thrust

本文关键字:二元 谓词 Thrust 理解      更新时间:2023-10-16

针对我之前的问题,有人给了我以下代码:

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()); 

我想了解谓词结构。如果操作符返回false会发生什么?哪个值被选中?如果操作符返回true会发生什么?哪个值被选中?

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

从我的评论:

我想我过度优化了代码。这是"小于"谓词。if条件计算false意味着一个或bool标志是false,所以我们需要排除相应的值。所以我们检查lhs参数是否应该排除(thrust::get<0>(lhs) == false),如果这是真的,谓词返回真,这意味着'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;