I have tried to create a template function that does some weighted sampling within a Monte Carlo simulation. It is below. input_data will either be a statically-allocated array (i.e. data[33]), a dynamically-allocated array, or a vector.
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];
}
The code will not compile because the template function could not deduce the argument for the call to sort. This may be a stupid question, but what do I need to do to ensure that sort can work properly?
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
Thanks in advance for your help.
If you put in an array, the array name is essentially a pointer to the first element, and the array
name + xis the poitner to thexth element – so you have this part correct.The problem is that this is not the case for a vector, which is why you need to use the
.begin()and.end()functions to get the pointer to these locations.You could try sorting by pulling the addresses of the dereferenced start/end elements – that might let you treat a vector the same as an array.