首页 新闻 会员 周边

为什么改为auto会报错得这样写才对function<void(string,string)>build=[&](string instr,string poststr)

0
[待解决问题]

include <bits/stdc++.h>

using namespace std;

int main() {
string instr, poststr;
cin >> instr >> poststr;

auto build = [](string instr, string poststr) {
    if(instr.size() <= 0) return;
    
    cout << poststr.back();
    int mid = instr.find(poststr.back());
    
    build(instr.substr(0, mid), poststr.substr(0, mid));
    build(instr.substr(mid + 1), poststr.substr(mid, poststr.size() - instr.size() + mid));
};

build(instr, poststr);

return 0;

}

lsming的主页 lsming | 菜鸟二级 | 园豆:202
提问于:2024-02-26 20:49
< >
分享
所有回答(1)
0

在你的代码中,build 函数是一个 lambda 表达式,它需要在调用之前声明。你已经在调用之前声明了 lambda 函数,但是你忘记了声明它的类型。在你的代码中,build 的类型是一个匿名的函数对象,它接受两个 string 类型的参数并且没有返回值,所以你应该将其类型声明为 function<void(string, string)>。

这里是你修正后的代码:

cpp
Copy code

include <bits/stdc++.h>

using namespace std;

int main() {
string instr, poststr;
cin >> instr >> poststr;

function<void(string, string)> build = [&](string instr, string poststr) {
    if (instr.size() <= 0) return;

    cout << poststr.back();
    int mid = instr.find(poststr.back());

    build(instr.substr(0, mid), poststr.substr(0, mid));
    build(instr.substr(mid + 1), poststr.substr(mid, poststr.size() - instr.size() + mid));
};

build(instr, poststr);

return 0;

}
在这个修正后的代码中,build 的类型被声明为 function<void(string, string)>,以确保 lambda 函数的类型被正确识别和使用。

Technologyforgood | 园豆:5686 (大侠五级) | 2024-02-28 17:42
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册