我試圖創建一個模板函數,在Monte Carlo模擬中進行一些加權採樣。在下面。 input_data將是一個靜態分配的數組(即data [33]),一個動態分配的數組或一個向量。使用STL在模板函數內排序?
template <class myType>
int init_roulette_calcs(myType &input_data, int inputlength, int *(&output_cdf), int highclassix, int weight)
{
sort(input_data, input_data + inputlength); //where the error occurs
//other code:
output_cdf = new int [inputlength];
int k = 1;
for (int i = 0; i < inputlength; i++)
{
output_cdf[i] = k;
if (i+1 < highclassix) k++;
else k += weight;
}
return output_cdf[inputlength-1];
}
該代碼不會編譯,因爲模板函數無法推斷調用進行排序的參數。這可能是一個愚蠢的問題,但我需要做些什麼才能確保這種排序可以正常工作?
Error 4 error C2784: 'std::_Vb_iterator<_Alloc> std::operator
+(_Alloc::difference_type,std::_Vb_iterator<_Alloc>)' : could not deduce template argument for
'std::_Vb_iterator<_Alloc>' from 'int' j:\rdm\lrgv_2011-07-21\lrgv_src\lrgv.h 398
在此先感謝您的幫助。
謝謝。我將不得不以不同的方式處理這些矢量。 – Joe
您不應該將STL迭代器視爲原始指針,否則您的代碼可能會在某些實現中斷裂。 –
我同意這種說法 - 矢量實現被定義爲在標準中使用連續內存,所以用指針算術來處理它們不應該產生問題。但是,對於STL容器來說,這確實不是一個好習慣 - 尤其是因爲在使用過程中迭代器可能會被容器操作無效化。 –