2013-08-23 5 views
0

string을 분리하고 각각의 필드를 vector 안에 넣는 토크 나이저를 작성했습니다. 내 생각은 string::find 반복적으로 사용하는 것이었다. 임시객체를 사용하는 대신에 move_iterator을 사용했습니다. 원래 문자열은 알고리즘이 처리 할 때 문자가 도난당하는 것을 보았습니다. 그러나 그것은 일어나지 않았다.C++ - std :: string and move_iterator

#include <vector> 
#include <string> 
#include <iostream> 

using namespace std; 

void 
print_strings 
    (const vector<string> & v) 
{ 
    unsigned int i = 1; 
    for (const auto & s : v) 
     cout << "#" << i++ << "\t: \"" << s << "\"" << endl; 
    return; 
} 

int 
main 
    (void) 
{ 
    string base("hello, this is an example string, I like icescreams"); 

    /* Vector to populate with strings */ 
    vector<string> v; 

    /* 1: a copy of 'base' */ 
    v.emplace_back(base); 
    /* 2: a copy of 'base' using iterators */ 
    v.emplace_back(base.begin() , base.end()); 
    /* 3: a string that I think _should_ move from 'base' */ 
    v.emplace_back(make_move_iterator(base.begin()) , make_move_iterator(base.end())); 

    /* Print the strings twice so that we 
    * can see if something has changed. */ 
    print_strings(v); 
    print_strings(v); 

    return 0; 
} 

g++ -std=c++11 -Wall -Wextra -Werror -O2 컴파일, 그것은 어떤 경고를 보여줍니다 :

내가 무슨 말을하는지 보여주는 예제 코드입니다.

내 생각에 string의 생성자는 범위 인 버전이며 항상 지정된 범위에서 복사됩니다. 확실하지는 않지만 사용하고 싶은 해결 방법을 확인하고 싶습니다.

안부, Kalrish

+0

'char'에서 이동하는 것은 그것으로부터 복사하는 것과 같습니다. 또한'base'를 인쇄하여 변경된 사항이 있는지 확인하지 않습니다. – jrok

+0

@jrok 실제로, 나는 그것을 잊었다. 이제 시도해 보았습니다.'base'가 수정되지 않았다고 말할 수 있습니다. – Kalrish

+0

그 샘플에는 단일의 값이 없습니다. –

답변

0

는 반복자는 컨테이너에 대해 아무것도 몰라.

move_iterator 문자열에서 마술처럼 움직일 수 없습니다. 그것은 기본 요소 인 char이고 char에서의 이동은 복사하는 것과 동일합니다. std::move(base)을 사용해야합니다.

#include <vector> 
#include <string> 
#include <iostream> 

using namespace std; 

void 
print_strings 
    (const vector<string> & v) 
{ 
    unsigned int i = 1; 
    for (const auto & s : v) 
     cout << "#" << i++ << "\t: \"" << s << "\"" << endl; 
    return; 
} 

int 
main 
    (void) 
{ 
    string base("hello, this is an example string, I like icescreams"); 

    /* Vector to populate with strings */ 
    vector<string> v; 

    /* 1: a copy of 'base' */ 
    v.emplace_back(base); 
    /* 2: a copy of 'base' using iterators */ 
    v.emplace_back(base.begin() , base.end()); 
    /* 3: a string that I think _should_ move from 'base' */ 

    std::cout << base << '\n'; // base is still untouched here 

    v.emplace_back(std::move(base)); // now it'll be moved from 

    print_strings(v); 
    std::cout << "base: " << base << "/base\n"; // base is empty 
    return 0; 
} 

라이브보기 here.

+0

문제는 전체 문자열이 아닌 범위에서 이동하고 싶다는 것입니다. – Kalrish

+0

이미'move_iterator'로 개념적으로 그렇게했습니다. 그것은 단지'std :: string'으로 많은 것을 얻지 못한다는 것입니다. 당신이 원했던 것 (나는 생각한다)은 문자열 버퍼의 일부를 "훔치는"것이다. 그럴 수 없어, 나는 두렵다. – jrok

+0

당신이 진술 한대로 가능하지 않다면, 나는이 질문이 의미가 없다고 생각합니다. 나는 임시 직원과 함께 갈거야. 도와 줘서 고마워! – Kalrish