使用Thrust库是否可以对对象进行排序? 我有以下结构体:
struct OB{
int N;
Cls *C; //CLS is another struct.
}
是否可以使用Thrust根据N对OB数组进行排序?您能提供一个使用Thrust对对象进行排序的简单示例吗?如果Thrust无法实现此功能,是否有其他CUDA库可以实现?
thrust::sort的文档显示它接受一个比较运算符。请在他们的示例中查看如何定义和使用这些操作符。虽然我没有测试过,但基于这个例子,你只需要一个类似这样的结构体:
struct OBCmp {
__host__ __device__
bool operator()(const OB& o1, const OB& o2) {
return o1.N < o2.N;
}
};
然后只需调用 thrust::sort(obs.begin(), obs.end(), OBCmp())
。
struct OB{
int N;
Cls *C; //CLS is another struct.
}
to
struct OBs{
int []Ns; -> thrust::device_vector<int> indices;
Cls *C[]; -> thrust::device_vector<Cls> values;
}
thrust::sort_by_key(indices.begin(), indices.end(), values.begin());
你可以通过重载运算符<来对对象进行排序。例如:
__host__ __device__ struct Color{
double blue, green, red;
double distance;
void dist()
{
distance = sqrt(blue*blue + green*green + red*red);
}
};
__host__ __device__ bool operator<(const Color &lhs, const Color &rhs)
{
return lhs.distance < rhs.distance;
}
int main(void)
{
thrust::device_vector<Color> cd;
thrust::host_vector<Color> ch;
for (int i = 0; i<6; i++)
{
Color c;
c.blue = rand()*255;
c.green = rand()*255;
c.red = rand()*255;
c.dist();
ch.push_back(c);
}
cd = ch;
thrust::sort(cd.begin(), cd.end());
ch = cd;
return 0;
}
这些对象将根据距离进行排序。
到目前为止,您无法对自定义对象进行排序。您可以进行基于键的排序,但不能对自定义对象(如您提到的结构体)进行排序。还有一些其他基于CUDA的开放算法可用于执行此操作,但这也需要进行一些修改等才能使它们适用于您。