gpt4 book ai didi

c++ - "error: subscripted value is not an array, pointer, or vector"我正在使用一个字符串

转载 作者:行者123 更新时间:2023-11-27 22:44:40 31 4
gpt4 key购买 nike

我正在为zoj 1733写一个程序,问题在第8行:

else if(x[i] == y[j])return f(i-1,j-1)+1;

为什么我不能在 x 是字符串时使用“x[i]”?而且我不明白提示“下标值不是数组、指针或 vector ”。以下是我的代码:

#include <iostream>
using namespace std;

string x,y;
int f(int i,int j){
int x,y;
if(i==0 || j==0)return 0;
else if(x[i] == y[j])return f(i-1,j-1)+1;
else {
x=f(i-1,j);
y=f(i,j-1);
if(x>y)return x;
else return y;
}
}
int main(int argc, char *argv[]) {
int i,j;
while(cin>>x>>y){
i=x.size();j=y.size();
cout<<f(i,j)<<endl;
}
return 0;
}

最佳答案

您将xy 声明为字符串全局变量,也声明为整型局部变量。当您在函数内部访问它们时,它会考虑整数版本,因为它们在更近的范围内。更改其中任何一个的名称,它应该可以正常工作。

编辑:“其中一个”是指更改全局变量或局部变量的名称,而不是 x 或 y :)

您还可以使用 ::x::y 引用函数内部的全局变量。这将通知编译器访问全局变量,但我真的建议只更改变量名称。

关于c++ - "error: subscripted value is not an array, pointer, or vector"我正在使用一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44666314/

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