鱼C论坛

 找回密码
 立即注册
查看: 154|回复: 1

为什么改为auto会报错得这样写才对

[复制链接]
发表于 2024-2-26 21:02:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include <bits/stdc++.h>
  2. using namespace std;

  3. int main() {
  4.     string instr, poststr;
  5.     cin >> instr >> poststr;
  6.    
  7.     auto build = [&](string instr, string poststr) { //为什么改为auto会报错得这样写才对function<void(string,string)>build=[&](string instr,string poststr)
  8.         if(instr.size() <= 0) return;
  9.         
  10.         cout << poststr.back();
  11.         int mid = instr.find(poststr.back());
  12.         
  13.         build(instr.substr(0, mid), poststr.substr(0, mid));
  14.         build(instr.substr(mid + 1), poststr.substr(mid, poststr.size() - instr.size() + mid));
  15.     };
  16.    
  17.     build(instr, poststr);
  18.    
  19.     return 0;
  20. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-2-26 21:03:08 | 显示全部楼层
在C++中,使用`auto`关键字来自动推导变量的类型是一种方便的特性。但是,在你的代码中,不能直接使用`auto`来定义一个函数。

在这种情况下,你需要显式指定函数的返回类型。这可以通过在函数定义前面添加返回类型来实现,如下所示:

  1. string build(string instr, string poststr) {
  2.     // 函数体
  3. }
复制代码


这样,编译器就能正确地推导出函数的返回类型,并且你可以在函数体内进行处理并返回该类型的值。

另外,你还需要注意函数参数的传递方式。在你的代码中,函数的参数名与`main`函数中的同名变量产生了冲突。为了避免这种冲突,你可以选择更改其中一个变量的名称,或者使用不同的作用域来解决该问题。这里我为你提供了一种修改的方法:

  1. #include <iostream>
  2. using namespace std;

  3. string build(string instr, string poststr) {
  4.     // 函数体
  5. }

  6. int main() {
  7.     string instr, poststr;
  8.     cin >> instr >> poststr;

  9.     string result = build(instr, poststr);
  10.     cout << result << endl;

  11.     return 0;
  12. }
复制代码


在这个修改后的代码中,函数`build`接受两个`string`类型的参数,并返回一个`string`类型的结果。在`main`函数中,我们调用`build`函数,将输入的字符串作为参数,并将返回的结果存储在`result`变量中,最后输出该结果。

希望能帮到你!如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 11:58

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表