在模板函数中使用STL排序
Using STL Sort within a template function?
我试图创建一个模板函数,在蒙特卡洛模拟中进行一些加权采样。它在下面。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);
^^^ ^^^
我希望您传递的参数实际上是对数组中第一个元素的引用。
相关文章:
- C++ STL 排序会检查 NaN 吗?
- 如何使用 STL 排序对具有模板专用化的自定义类对象进行排序?
- C++ wrt 字符串中的 STL 排序函数
- 如何检查队列是否使用 STL 排序
- C :STL STL阵列的STL排序
- STL 排序,保留原始顺序
- 当我们在C 中已经可以使用STL排序功能时,为什么我们需要学习不同的排序算法
- 无法以STL排序解析对向量的对向量的模板
- 为什么使用STL排序()进行二次时间排序
- 如何使用stl排序函数根据第二列对2d数组进行排序
- 我正在尝试为我的 DynamicArray 类创建一个迭代器。为什么 STL 排序不适用于我的迭代器?
- C++ 运算符重载:对我的自定义类的向量进行 stl 排序
- 使用 STL 排序对表进行排序
- stl排序比较类函数
- 重载比较运算符以使用C++中的STL排序
- 为什么我的重载<运算符不适用于 STL 排序
- STL排序在字符串矢量与字符串指针矢量上的性能比较
- 如何编写带有中间变量的比较器以进行 stl 排序
- 我如何使用c++库函数或STL排序字符串
- STL排序使用交换还是二进制拷贝?