[英]Custom min operator for thrust::tuple in reduction
我試圖在zip迭代器上運行min min,但是使用自定義運算符只考慮元組中的第二個字段(第一個字段是鍵,而第二個字段,值,實際上與減少)
但是,我無法使其工作,並且當前正在計算向量中存在的結果
以下代碼重現了該問題:
#include <thrust/device_vector.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/tuple.h>
#include <thrust/sequence.h>
typedef thrust::tuple<unsigned int, unsigned int> DereferencedIteratorTuple;
struct tuple_snd_min{
__host__ __device__
bool operator()(const DereferencedIteratorTuple& lhs,
const DereferencedIteratorTuple& rhs){
return (thrust::get<1>(lhs) < thrust::get<1>(rhs));
}
};
void f(){
thrust::device_vector<unsigned int> X(10);
thrust::device_vector<unsigned int> Y(10);
thrust::sequence(X.begin(), X.end());
thrust::sequence(Y.begin(), Y.end());
X[0] = 5;
Y[0] = 5;
X[1] = 50;
// X: 5 50 2 3 4 5 6 7 8 9
// Y: 5 1 2 3 4 5 6 7 8 9
typedef thrust::device_vector<unsigned int>::iterator UIntIterator;
typedef thrust::tuple<UIntIterator, UIntIterator> IteratorTuple;
thrust::zip_iterator<IteratorTuple> first =
thrust::make_zip_iterator(thrust::make_tuple(X.begin(), Y.begin()));
thrust::tuple<unsigned int, unsigned int> init = first[0];
thrust::tuple<unsigned int, unsigned int> min =
thrust::reduce(first, first + 10, init, tuple_snd_min());
printf("(%d,%d)\n", thrust::get<0>(min), thrust::get<1>(min));
// should return (50,1)
// returns (0,0)
}
感謝Jared Hoberock的評論,我能夠解決這個問題。
typedef thrust::tuple<unsigned int, unsigned int> DereferencedIteratorTuple;
struct tuple_snd_min{
__host__ __device__
const DereferencedIteratorTuple& operator()(const DereferencedIteratorTuple& lhs, const DereferencedIteratorTuple& rhs)
{
if(thrust::get<1>(lhs) < thrust::get<1>(rhs)) return lhs;
else return rhs;
}
};
這似乎是由於對reduce
調用中的functor必須實現哪個操作的誤解造成的。 根據文檔 ,仿函數必須是二元函數的模型,其輸出必須可轉換為輸入類型。 這是你的算子失敗的地方。 而不是這個
struct tuple_snd_min{
__host__ __device__
bool operator()(const DereferencedIteratorTuple& lhs,
const DereferencedIteratorTuple& rhs){
return (thrust::get<1>(lhs) < thrust::get<1>(rhs));
}
};
您的仿函數需要定義如下:
struct tuple_snd_min{
__host__ __device__
int operator()(const DereferencedIteratorTuple& lhs,
const DereferencedIteratorTuple& rhs){
return (thrust::get<1>(lhs) < thrust::get<1>(rhs)) ?
thrust::get<1>(lhs) : thrust::get<1>(rhs);
}
};
即函數應該返回一個值而不是作為謂詞。
[這個答案是根據評論匯總而成,並作為社區維基條目發布,以便將此問題從未答復的隊列中刪除]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.