【发布时间】:2020-12-04 02:48:34
【问题描述】:
我在 C++ 中练习 lambda 函数,下面的代码运行良好
void insertionSort(int* a, int size, bool reverse=false) {
auto comp = [](int a, int b, bool reverse) {
return reverse ? a > b : b < a;
};
for (int i = 0; i < size; i++) {
int current = a[i];
cout << current <<endl;
int j = i-1;
while (j >= 0 && comp(current, a[j], reverse)) {
a[j+1] = a[j]; //shift right
j--;
}
a[j+1] = current;
}
show(a, size); //another function which prints all elements of a
}
但如果我改变了
auto comp = [](int a, int b, bool reverse) {
与
bool comp = [](int a, int b, bool reverse) {
GCC 编译器在编译时抛出以下错误
error: 'comp' cannot be used as a function 29 | while (j >= 0 && comp(current, a[j], reverse)) {
这是预期的吗?什么是一般规则?我是否应该始终将返回类型指定为auto?
【问题讨论】:
-
auto comp = [](int a, int b, bool reverse) -> bool {} 这就是你如何用 bool 返回类型声明 lambda。您要更改的 auto 是 lambda 本身的类型。