设置A = B是否与B混乱?(所有向量)C++

Chr*_*Ahm 0 c++ vector copying

我正在制作一个匹配两个字符串向量的函数.作为该功能的一部分,我需要制作载体的副本.我想在函数的开头做这个,但不知何故,如果我这样做,它会使我的函数崩溃.这就是我想要设置的功能

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,一个简单的开关使功能工作,我不明白为什么

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Vit*_*meo 7

vector<string> u1=u;
u1.erase(u1.begin());
Run Code Online (Sandbox Code Playgroud)

如果u.size() == 0那么u1.begin() == u1.end().调用vector<string>::erase未指向现有元素的迭代器是未定义的行为.