gpt4 book ai didi

c++ - 设置 A=B 是否会以某种方式混淆 B? (所有 vector )C++

转载 作者:太空宇宙 更新时间:2023-11-04 15:13:32 24 4
gpt4 key购买 nike

我正在创建一个匹配两个字符串 vector 的函数。作为该功能的一部分,我需要制作 vector 的拷贝。我想在函数的开头这样做,但不知何故,如果我这样做,它会使我的函数崩溃。这就是我想要设置功能的方式

vector<string> match(vector<string> & u,vector<string> & v){

// I would like to define these first, but that crashes my function
vector<string> u1=u;
vector<string> v1=v;
u1.erase(u1.begin());
v1.erase(v1.begin());
// I would like to define these first, but that crashes my function

if(u.size()==0){
return u;
}
if(v.size()==0){
return v;
}

if(u.at(0)==v.at(0)){
vector<string>result=match(u1,v1);
result.insert(result.begin(),u[0]);
return result;
}

if(match(u,v1)>=match(u1,v)){
vector<string>result= match(u,v1);
return result;
}

else{
return match(u1,v);
}
}

然而,一个简单的开关确实使该功能起作用,我不明白为什么

vector<string> match(vector<string> & u,vector<string> & v){

//Putting these if statements first makes the function work
if(u.size()==0){
return u;
}
if(v.size()==0){
return v;
}
//Putting these if statements first makes the function work

vector<string> u1=u;
vector<string> v1=v;
u1.erase(u1.begin());
v1.erase(v1.begin());



if(u.at(0)==v.at(0)){
vector<string>result=match(u1,v1);
result.insert(result.begin(),u[0]);
return result;
}

if(match(u,v1)>=match(u1,v)){
vector<string>result= match(u,v1);
return result;
}

else{
return match(u1,v);
}
}

最佳答案

vector<string> u1=u;
u1.erase(u1.begin());

如果u.size() == 0然后u1.begin() == u1.end() .打电话vector<string>::erase在不指向现有元素的迭代器上是未定义的行为

关于c++ - 设置 A=B 是否会以某种方式混淆 B? (所有 vector )C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43921286/

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