2012-06-13 81 views
1

我使用推力::序列 - 如何提高每個N元素後一步

thrust::sequence(myvector.begin(), myvector.end(), 0, 1) 

並取得良好的有序列表,如:

0, 1, 2, 3, 4 

我的問題是如何實現這樣的下面列舉(最好的方法是什麼?)

0, 0, 0, 1, 1, 1, 2, 2 ,2, 3, 3, 3 

我知道如何與函子做,所以請不要試圖用函子來回答。我想了解,如果有一個優化的方式爲它的推力,還是我失去了一個簡單的方法..

回答

4

事情是這樣的:

thrust::device_vector<int> myvector(N); 

thrust::transform(thrust::make_counting_iterator(0), 
        thrust::make_counting_iterator(N), 
        thrust::make_constant_iterator(3), 
        myvector.begin(), 
        thrust::divides<int>()); 

(免責聲明寫在瀏覽器中,從來沒有編譯或測試,請自擔風險)

應通過計算[0..N]//3並在myvector上輸出結果來給出您要查找的序列。


看到,因爲你有麻煩編譯您的版本,這裏是編譯和完整的示例運行:

#include <thrust/device_vector.h> 
#include <thrust/transform.h> 
#include <thrust/functional.h> 
#include <thrust/iterator/counting_iterator.h> 
#include <thrust/iterator/constant_iterator.h> 
#include <cstdio> 

int main(void) 
{ 
    const int N = 18, M = 3; 
    thrust::device_vector<int> myvector(N); 

    thrust::transform( thrust::make_counting_iterator(0), 
         thrust::make_counting_iterator(N), 
         thrust::make_constant_iterator(M), 
         myvector.begin(), 
         thrust::divides<int>()); 

    for(int i=0; i<N; i++) { 
     int val = myvector[i]; 
     printf("%d %d\n", i, val); 
    } 
    return 0; 
} 
+0

尼斯的答案,但我不能編譯:xyz.cu(544) :error:沒有重載函數的實例「thrust :: transform」匹配參數列表參數類型是:(thrust :: counting_iterator ,thrust :: counting_iterator ,thrust :: constant_iterator ,thrust :: detail :: normal_iterat或>,thrust :: divides ) – phoad

+0

您是否閱讀過錯誤信息?你已經爲常量和計數迭代器參數混合了'unsigned int'和'int'類型。我已經編輯了一個可編輯的例子,它可以正確運行,供你學習。 – talonmies

+1

是的,我很驚訝,因爲得到這樣的錯誤,並錯過了unsigned int vs int不匹配。很好的結果,答案和錯誤。謝謝。 – phoad

相關問題