gpt4 book ai didi

c++ - C++排序自适应函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:28:27 24 4
gpt4 key购买 nike

我想为不同类型的不同集合创建自适应冒泡排序功能。代码示例:

#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::function,std::function 的模板参数不能从 lambda 的参数推导出来。

但是您不需要将 std::function 作为比较器,模板“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++ - C++排序自适应函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51347018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com