2013-11-02 2 views
0

은 code :: blocks에서 .cpp를 열려고 시도했습니다. 오류의 몇 줄을 얻었다std :: string {aka std :: basic_string <char>} '대입의'char * '로 |

부분 코드 : 나는 라인이 오류를받을

void QSort(string List[], int Left, int Right) 
{ 
    int i, j; 
    char *x; 
    string TEMP; 

    i = Left; 
    j = Right; 
    x = List[(Left+Right)/2]; 

    do { 
    while((strcmp(List[i],x) < 0) && (i < Right)) { 
     i++; 
    } 
    while((strcmp(List[j],x) > 0) && (j > Left)) { 
     j--; 
    } 
    if(i <= j) { 
     strcpy(TEMP, List[i]); 
     strcpy(List[i], List[j]); 
     strcpy(List[j], TEMP); 
     i++; 
     j--; 
    } 
    } while(i <= j); 

    if(Left < j) { 
    QSort(List, Left, j); 
    } 
    if(i < Right) { 
    QSort(List, i, Right); 
    } 
} 

x = List[(Left+Right)/2]; 

'표준 : : 문자열 {일명 표준 : : basic_string}'로 변환 할 수 없습니다 'char *' 과제에서 |

+0

가능 중복 된 [I가 문자 유형의 배열에 표준 : 기본 \의 _string 형식을 변환 할 수 있습니까?] (http://stackoverflow.com/questions/12978201/how-can-i-convert -a-stdbasic-string-type-of-char-type) – kfsone

+0

[사전 식 비교] (http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp)를 사용하지 않는 이유는 무엇입니까?)'std :: string'에 대한 연산자? –

답변

2

호환되지 않기 때문입니다. std::string으로 전화하여 const char*을 반환해야합니다.

주의 :이 포인터는 std :: string의 유효 기간 동안 또는 문자열 개체를 수정할 때까지만 유효합니다.

이 함수는 const char*을 반환하므로 x의 정의를 char*에서 'const char *'로 변경해야합니다.

const char* x; 

또는 더 나은 아직, 그 줄을 제거하고, 두

void QSort(string List[], int Left, int Right) 
{ 
    string TEMP; 

    int i = Left; 
    int j = Right; 
    const char* x = List[(Left+Right)/2]; 

Infact는 결합, 여기 (대신 strcmp와의 비교 :: 표준 : : 문자열)를 통해 표준 C++ 알고리즘을 사용하여 재 작성합니다. 이렇게하면 알고리즘 자체에 더 쉽게 집중할 수 있습니다.

void QSort(string List[], int Left, int Right) 
{ 
    int i = Left; 
    int j = Right; 
    const int mid = (Left+Right)/2; 

    for (;;) // repeat until we break. 
    { 
     // write both comparisons in terms of operator < 
     while (List[i].compare(List[mid]) < 0 && i < Right) 
      ++i; 
     while (List[mid].compare(List[j]) < 0 && Left < j) 
      --j; 
     // if i == j then we reached an impasse. 
     if (i >= j) 
      break; 
     std::swap(List[i], List[j]); 
    } 

    if(Left < j) 
    QSort(List, Left, j); 

    if(i < Right) 
    QSort(List, i, Right); 
} 
+0

필자는 컴파일러 문제, 많은 코드 줄이 영향을받는다고 생각합니다. 다른 해결책이 있습니까? –

+1

이것은 컴파일러 문제가 아닙니다. 'std :: string'을 호환되지 않기 때문에'const char *'로 변환 할 수 없습니다. std :: string이 관리하고있는'const char * '를 얻기 위해서는 string의'c_str()'메소드를 호출해야한다. – kfsone

+0

'string'이라는 이름을 혼동하지 마십시오 :'std :: string'는 클래스 이름입니다. 'std :: string foo = "hello";'는 완전히 다른 짐승입니다.''char foo [] = "hello";''char * foo = "hello";'는 C 스타일의 문자열입니다. – kfsone

관련 문제