在模板函数中使用STL排序

Using STL Sort within a template function?

本文关键字:STL 排序 函数      更新时间:2023-10-16

我试图创建一个模板函数,在蒙特卡洛模拟中进行一些加权采样。它在下面。input_data将是静态分配的数组(即data[33](、动态分配的数组或向量。

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];
}

代码将不会编译,因为template函数无法推导出调用sort的参数。这可能是一个愚蠢的问题,但我需要做什么才能确保sort正常工作?

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:rdmlrgv_2011-07-21lrgv_srclrgv.h  398

提前感谢您的帮助。

如果放入一个数组,数组名称本质上是指向第一个元素的指针,而数组name + x是指向第x个元素的指向器,所以这部分是正确的。

问题是,向量的情况并非如此,这就是为什么需要使用.begin().end()函数来获取指向这些位置的指针。

您可以尝试通过提取未引用的起始/结束元素的地址来进行排序,这可能会让您将向量视为数组。

在代码中,input_data是一个引用,但排序需要它是指向数组开头的指针。应该是:

int init_roulette_calcs(myType input_data[], int inputlength, …

尽管制作这样一个模板是正确的STL用法,用户可以提供任何类型的随机访问开始和结束迭代器。因此,您可以稍后切换到向量或任何其他排序可以在上工作的容器

template <class InputIterator>
int init_roulette_calcs(InputIterator begin, InputIterator end, int *(&output_cdf), int highclassix, int weight)
sort(&input_data, &input_data + inputlength);
    ^^^          ^^^    

我希望您传递的参数实际上是对数组中第一个元素的引用。