C++中排序的自适应功能
Adaptive function of sorting in C++
我想创建一个函数,用于对不同类型的不同集合进行自适应冒泡排序。代码示例:
#include <iostream>
#include <vector>
#include <functional>
template <typename CollectionType, typename ValueType>
void bubbleSort(CollectionType& ar, size_t size, std::function<bool(ValueType, ValueType)> comparator)
{
bool isSorting = false;
for (size_t i = 0; i < size - 1; i++)
{
isSorting = true;
for (size_t j = 0; j < size; j++)
{
if (comparator(ar[j], ar[j + 1]))
{
std::swap(ar[j], ar[j + 1]);
isSorting = false;
}
}
if (isSorting)
{
return;
}
}
}
int main()
{
std::vector<int> vector = {7, 9, 1, 5, 8, 1, 8, 3, 7, 3};
bubbleSort(vector, vector.size(), [](int a, int b) { return a > b; });
for(const auto& val : vector)
{
std::cout << val << " ";
}
return EXIT_SUCCESS;
}
但我遇到了以下问题:
/home/vova/Desktop/Temp/main.cpp:37:73: error: no matching function for call to ‘bubbleSort(std::vector<int>&, std::vector<int>::size_type, main()::<lambda(int, int)>)’ bubbleSort(vector, vector.size(), [](int a, int b) { return a > b; });
/home/vova/Desktop/Temp/main.cpp:6:6: note: candidate: template<class CollectionType, class ValueType> void bubbleSort(CollectionType&, size_t, std::function<bool(ValueType, ValueType)>) void bubbleSort(CollectionType& ar, size_t size, std::function<bool(ValueType, ValueType)> comparator)
/home/vova/Desktop/Temp/main.cpp:6:6: note: template argument deduction/substitution failed:
/home/vova/Desktop/Temp/main.cpp:37:73: note: ‘main()::<lambda(int, int)>’ is not derived from ‘std::function<bool(ValueType, ValueType)>’ bubbleSort(vector, vector.size(), [](int a, int b) { return a > b; });
如果我为函数设置模板的参数:
bubbleSort<std::vector<int>, int>(...)
然后它就起作用了,但对我来说并不漂亮。它怎么能纠正呢?
您的lambda不是std::函数,并且std:::函数的模板参数不能从lambda的参数中推导出来。
然而,您不需要使用std::函数作为比较器,模板"comparator"参数就可以了。这就是标准库对有序容器中的比较器所做的。例如
template <typename CollectionType, typename Comparitor>
void bubbleSort(CollectionType& ar, size_t size, Comparitor comparator)
{
bool isSorting = false;
for (size_t i = 0; i < size - 1; i++)
{
isSorting = true;
for (size_t j = 0; j < size; j++)
{
if (comparator(ar[j], ar[j + 1]))
{
std::swap(ar[j], ar[j + 1]);
isSorting = false;
}
}
if (isSorting)
{
return;
}
}
}
相关文章:
- 如何检查助推融合序列是否为自适应结构
- C++中排序的自适应功能
- Boost.Spirit.Qi 语法,用于 Boost.Fusion 自适应结构中的默认值
- 自适应路径 - 阿斯塔尔修改
- 具有自适应 std::p air 点类型的 R 树查询
- 如何自定义功能行为
- 如何在自定义功能中使用C 构建器OpenArray
- 将自适应阈值应用于范围函数 opencv c++
- 使用C 使用PayPal自适应付款API的最佳方法是什么?
- 自定义功能不返回正确的值
- 全部使用用户自定义功能和MPI_BOTTOM
- 将 Rcpp 与 C 代码链接,以实现自适应城域拒绝采样
- 采用 Opencv c++ 的自适应中值滤波器
- 自适应正交 (C++)
- Boost Spirit Parser用三个字符串的矢量编译成一个结构,自适应不工作
- OpenCV / C++ - 如何在矢量上使用自适应阈值而不是垫子
- 您将如何在调度程序中实现这种自适应的"软糖因子"?
- OpenCV中的自适应算法实现
- 用自适应MeanShift对特征空间-SURF描述符进行聚类
- 自适应阈值opencv