我正在尝试为 qsort 的比较器创建一个内联函数 - 如下所示:
function<int(int,int)> comparesort = [smarkers, emarkers, strSearch] (int *arg1, int *arg2) { return 0; };
qsort(sortptrs, nKeywords, sizeof(int), comparesort);
它给我这个错误
IntelliSense:不存在从“std::tr1::function”到“int (__cdecl *)(const void *, const void *)”的合适转换函数
好的 - 我把它改成了这个
auto comparesort = [sortptrs, smarkers, emarkers, strSearch] (int arg1, int arg2)
{
int a = 0;
.
.
.
return a;
};
std::sort(sortptrs, sortptrs + nKeywords, comparesort);
它给出了一个错误:
错误 C3499:指定为具有 void 返回类型的 lambda 无法返回值
[编辑于 7 月 30 日下午 3:55]
我实际上需要一个指针排序 - 我有一个单词的开始和结束字节数组(在从 VB.Net 托管代码传入的字符串中找到)。我还有一个包含“1,2,3...”的指针数组,我需要对指针进行排序。
我似乎无法使用 std::sort 做到这一点,所以我实现了自己的 shell 排序...
最佳答案
qsort
的签名采用 int(*)(const void*, const void*)
类型的函数指针.你试图给它一个 function<int(int, int)>
,它不是一个函数指针,而是一个封装了某些东西的对象(可能是一个函数 ptr,可能是一个仿函数),它可以作为 int(int, int)
调用。 (注意它不会有正确的签名,即使它是一个函数指针)。
qsort
基本上是一个与 c 向后兼容的遗留函数。
在 C++ 中,我强烈建议忘记它并使用 std::sort
相反:
auto comparesort = [smarkers, emarkers, strSearch] (const int& arg1, const int& arg2) { return false; };
//directly store the lambda, avoiding the overhead of creating a `function<...>`
std::sort(sortptrs, sortptrs + nKeywords, comparesort);
关于c++ - 尝试将 c++ qsort 与内联函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11713126/