在cuda中搜索int3类型的排序数组中的值

时间:2015-06-06 18:51:26

标签: search cuda parallel-processing thrust

排序数组的类型为int3

For example:
{1,2,3},{1,2,4},{1,3,4},{2,3,4}......

在cuda内核中,我需要搜索int3值并在排序数组中找到它的索引。

一种方法可能是使用binary search来查找值,但是如果条件可能会产生分歧,则需要为int3实施该值。

有没有一种有效的方法来做到这一点?

1 个答案:

答案 0 :(得分:1)

这可以很容易地完成。 以下代码使用thrust::find来查找数组中的值。 它使用自定义operator== should avoid分歧。

#include <thrust/device_vector.h>
#include <thrust/find.h>
#include <vector_types.h>

inline __host__ __device__
bool operator==(const int3& a, const int3& b)
{
    return (a.x == b.x) & (a.y == b.y) & (a.z == b.z);
    // alternatively
    // return (a.x == b.x) && (a.y == b.y) && (a.z == b.z);
}

int main()
{
    thrust::device_vector<int3> input(4);
    input[0] = make_int3(1,2,3);
    input[1] = make_int3(1,2,4);
    input[2] = make_int3(1,3,4);
    input[3] = make_int3(2,3,4);

    thrust::device_vector<int3>::iterator iter;
    iter  = thrust::find(input.begin(), input.end(), make_int3(1,3,4));
    int index = iter-input.begin();
    std::cout << "index = " << index << std::endl;

    return 0;
}

输出:

index = 2