2017-05-11 6 views
0

Im은 두 개의 문자열 벡터와 일치하는 함수를 만듭니다. 그 기능의 일부로 벡터 사본을 만들어야합니다. 함수의 시작 부분에서 그렇게하고 싶습니다만, 어떻게 든 그렇게되면 함수가 충돌하게됩니다. 이것은 내가 그러나 내가 이해 해달라고 함수 작업을 만들 않는 기능A = B로 설정하면 B가 어찌 되었습니까? (모든 벡터) C++

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

복사 생성자 문제 ?? –

+0

이 코드의 상위 목표는 무엇입니까? 두 벡터에있는 항목을 포함하는 벡터를 반환하는 것입니까? 그렇다면이 코드 대신'std :: set_intersection'을 사용할 수 있습니다. 'std :: set_intersection'을 사용하면 @VittorioRomeo가 그의 대답에서 지적한 유효하지 않은 반복자를 잘못 실행시키지 않을 것입니다. – PaulMcKenzie

+0

일종의,하지만 개별 항목 배치뿐만 아니라 출력에 영향을 미칠 것으로 보인다. 나는 전반적인 목표가 무엇인지 말하지 않았으며, 재귀 적으로 산출물을 산출하는 조건의 목록 만 가지고있다. –

답변

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

u.size() == 0 다음 u1.begin() == u1.end()합니다. 기존 요소를 가리 키지 않는 반복자에서 vector<string>::erase을 호출하면 정의되지 않은 동작 인 입니다.

+0

아, 이런. 나는 그 시나리오를 고려하지 않았다. 고맙습니다 –