c++ - 怎么修错误:无法从“初始化列表”转换为 asdendingCompare(模板函子)
问题描述
我正在尝试使用模板仿函数(ascendingCompare)来比较两个值并在模板函数(Sort)中使用它来排序数组
函子
template<typename Q>
class ascendingCompare
{
public:
bool operator () (const Q &first, const Q &second)
{
if (first < second)
return true;
else
return false;
}
};
排序函数和交换值的函数
template <typename Q>
void Swap(Q &first, Q &second)
{
Q temp = first;
first = second;
second = temp;
}
template <typename W>
void sortAscend(W *arr, int size)
{
for (int i = 0; i < size - 1; i++)
for (int j = 0; j < size - 1 - i; j++)
if (ascendingCompare<W>( arr[j + 1], arr[j]) )
Swap(arr[j + 1], arr[j]);
/*if (arr[j + 1] < arr[j])
Swap(arr[j + 1], arr[j]);*/
}
使用仿函数的部分
int *sorted_array = new int[array_size];
for (int counter = 0; counter < array_size; counter++)
{
sorted_array[counter] = rand() % 100;
cout << setw(2) << sorted_array[counter] << " ";
}
sortAscend(sorted_array, array_size);
所以编译器给出了这个 C2440 错误:无法从“初始化列表”转换为“升序比较”
解决方案
如上回答
在尝试触发 operator() 之前,您从未创建过ascendingCompare 的实例。您的 asrendingCompare( arr[j + 1], arr[j]) 试图从这些参数中构造,这显然是错误的。
所以正确的形式是
template <typename W>
void sortAscend(W *arr, int size)
{
for (int i = 0; i < size - 1; i++)
for (int j = 0; j < size - 1 - i; j++)
if (ascendingCompare<W>()( arr[j + 1], arr[j]) )
Swap(arr[j + 1], arr[j]);
/*if (arr[j + 1] < arr[j])
Swap(arr[j + 1], arr[j]);*/
}
因此,如果您对实际发生的变化感到困惑
旧版本
if (ascendingCompare<W>( arr[j + 1], arr[j]) )
新诗
if (ascendingCompare<W>()( arr[j + 1], arr[j]) )
推荐阅读
- javascript - React 反模式,定义一个组件里面定义另一个组件
- php - Laravel 5. String Var 子句不起作用的地方
- jsonpath - 如何为可能具有两种不同类型的元素指定替代 json 路径
- android - 带有折叠工具栏的 CoordinatorLayout,NestedScrollView 和 RecyclerView 底部有空白空间(滚动太远)
- python - 员工 replace_employee 使用与 parent_id(直接经理)相同的访问权限和规则
- r - 来自 7 列 80 行的随机样本
- django - 如何在模型序列化器的创建方法中设置序列化器自定义字段?
- django - 选择模板中最新更新的评论
- haskell - Haskell中函数的尾递归
- c# - razor 服务器端的浏览器宽度