C++中排序的自适应功能

Adaptive function of sorting in C++

本文关键字:自适应 功能 排序 C++      更新时间:2023-10-16

我想创建一个函数,用于对不同类型的不同集合进行自适应冒泡排序。代码示例:

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