设置A=B是否会对B造成干扰?(所有向量)C++

设置A=B是否会对B造成干扰?(所有向量)C++,c++,vector,copying,C++,Vector,Copying,我正在制作一个匹配两个字符串向量的函数。作为该函数的一部分,我需要复制向量。我想在函数开始时这样做,但如果我这样做,不知怎的会使我的函数崩溃。这就是我想要设置函数的方式 vector<string> match(vector<string> & u,vector<string> & v){ // I would like to define these first, but that crashes my function vecto

我正在制作一个匹配两个字符串向量的函数。作为该函数的一部分,我需要复制向量。我想在函数开始时这样做,但如果我这样做,不知怎的会使我的函数崩溃。这就是我想要设置函数的方式

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);
    }
}

如果u.size==0,则u1.begin==u1.end。在不指向现有元素的迭代器上调用vector::erase是未定义的行为。

复制构造函数问题??此代码的高级目标是什么?是否返回一个包含两个向量中的项的向量?如果是这样,那么就可以使用std::set_intersection来代替所有这些代码。使用std::set_intersection不会让您与@VittorioRomeo在其答案中指出的无效迭代器发生冲突。我没有被告知总体目标是什么,只是一个条件列表,从中递归生成输出。如果这只是一个匹配,则返回匹配向量。最重要的是,如果你在为循环编写手工制作的代码,以完成之前多次完成的工作,那么很有可能有一个或多个STL算法函数可以完成这项工作,而无需为循环编写代码。啊,当然可以。我没有考虑到这种情况。非常感谢。
vector<string> u1=u;
u1.erase(u1.begin());