c++ - 如何在 thrust::sort 中使用结构数组?

标签 c++ arrays sorting cuda thrust

我是 CUDA 开发的新手,我正在尝试使用推力库的排序方法对结构数组进行排序。我的结构是这样的:

#define N 307200    
struct distanceVector {
   Point3D a, b;
   float distance;
};

我想按“距离”对数组进行排序,但是,排序函数需要两个随机访问迭代器,而且由于我没有使用 vector ,所以我没有任何 vector 。我试过这样做:

bool distance_sort(distanceVector A, distanceVector B){
   return (A.distance > B.distance);
}

distanceVector * MyStructArray;
cudaMalloc((void**)&MyStructArray, sizeof(distanceVector) * N);
//LAUNCH KERNEL WHICH FILLS MYSTRUCTARRAY AND THEN...
thrust::sort(MyStructArray, MyStructArray + N, distance_sort);

...我在 [thrust's guide][1] 中看到了一个例子:

#include <thrust/sort.h>
#include <thrust/functional.h>
...
const int N = 6;
int A[N] = {1, 4, 2, 8, 5, 7};
thrust::stable_sort(A, A + N, thrust::greater<int>());
// A is now {8, 7, 5, 4, 2, 1}

虽然它编译了,但在执行期间我得到了“读取位置 0x405e041c 的访问冲突”。错误。 在调试应用程序时,在 insertion_sort.h 文件的这一部分停止:

for(RandomAccessIterator i = first + 1; i != last; ++i)
  {
    value_type tmp = *i;

    if (wrapped_comp(tmp, *first)).......

有没有不使用推力 vector 就能解决这个问题的方法?

最佳答案

好的,所以我发现了我的错误。问题是我正在尝试对设备上分配的内存使用推力。我尝试先将 MyStructArray 复制到主机设备,然后使用 thrust 的排序,它工作得很好。为了处理设备的内存,我必须使用 thrust::device_ptr pointer(MyStructArray)。 希望这对其他人有帮助。

关于c++ - 如何在 thrust::sort 中使用结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21359666/

相关文章:

iphone - 从 NSDictionary 按排序顺序显示 JSON 字符串

C++ RadixSort 高效方式

c++ - DLL 中显示的对话框在 Qt Creator 项目中具有 Win98/Classic 样式控件,但在 Visual Studio 中主题正确

php - 多维 array_values 仅适用于整数键

python - numpy.append() 的困难。当我自己在 IDLE 中输入它时它有效,但在运行时无效

arrays - 在 Swift 中从文本文件加载数值数组

java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : -1 (Sort Condition)

c++ - 将 stringstream 的内容传递给以 char* 为参数的函数

c++ ofstream(someVariable) 初始化

c++ - 如何告诉 C++ 不要优化丢弃的表达式?