1

私はCUDAに取り組んでおり、次の問題に直面しています。次の配列構造があります。

typedef struct Edge{
    int *from, *to, *weight;
}

対応する「from」および「to」配列も更新されるように、この構造を重み配列でソートしたいと思います。Thrustライブラリを使用することを考えましたが、ベクターでしか機能しないことがわかりました。sort_by_key で 2 つの配列をソートできますが、3 つの配列をソートする方法がわかりません。zip_iterator も調べましたが、それを使用して目的を果たす方法がわかりませんでした。助けてください

4

1 に答える 1

2

最初に、構造を 1) キーと 2) パディングに分離します。次に、キーをソートし、それに応じてパディングを並べ替えます。たとえば、次の構造を壊します。

typedef struct Edge{
    int from, to, weight;
}

の中へ:

int weight[N];
typedef struct Edge{
    int from, to;
}

完全なコードは次のとおりです。

#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <cmath>
#include <thrust/sort.h>

typedef struct pad {
        int from;
        int to;
} padd;

__host__ padd randPad() {
        padd p;
        p.from = rand();
        p.to = rand();
        return p;
}

__host__ std::ostream& operator<< (std::ostream& os, const padd& p) {
        os << "(" << p.to << " , " << p.from << " )";
        return os;
}

int main(void)
{
  // allocation
  #define N 4
  thrust::host_vector<int> h_keys(4);
  thrust::host_vector<padd> h_pad(4);

  // initilization
  thrust::generate(h_keys.begin(), h_keys.end(), rand);
  thrust::generate(h_pad.begin(), h_pad.end(), randPad);

  // print unsorted data
  std::cout<<"Unsorted keys\n";
  thrust::copy(h_keys.begin(), h_keys.end(), std::ostream_iterator<int>(std::cout, "\n"));
  std::cout<<"\nUnsorted paddings\n";
  thrust::copy(h_pad.begin(), h_pad.end(), std::ostream_iterator<padd>(std::cout, "\n"));

  // transfer to device
  thrust::device_vector<int> d_keys = h_keys;
  thrust::device_vector<padd> d_pad = h_pad;
  //thrust::sort(d_keys.begin(), d_keys.end());

  // sort
  thrust::sort_by_key(d_keys.begin(), d_keys.end(), d_pad.begin());

  // transfer back to host
  thrust::copy(d_keys.begin(), d_keys.end(), h_keys.begin());
  thrust::copy(d_pad.begin(), d_pad.end(), h_pad.begin());

  // print the results
  std::cout<<"\nSorted keys\n";
  thrust::copy(h_keys.begin(), h_keys.end(), std::ostream_iterator<int>(std::cout, "\n"));
  std::cout<<"\nSorted paddings\n";
  thrust::copy(h_pad.begin(), h_pad.end(), std::ostream_iterator<padd>(std::cout, "\n"));

  return 0;
}

出力は次のようになります。

Unsorted keys
1804289383
846930886
1681692777
1714636915

Unsorted paddings
(424238335 , 1957747793 )
(1649760492 , 719885386 )
(1189641421 , 596516649 )
(1350490027 , 1025202362 )

Sorted keys
846930886
1681692777
1714636915
1804289383

Sorted paddings
(1649760492 , 719885386 )
(1189641421 , 596516649 )
(1350490027 , 1025202362 )
(424238335 , 1957747793 )
于 2012-10-22T12:39:12.560 に答える