2013-11-02 77 views
0

試圖在code :: blocks中打開一個.cpp文件。遇到錯誤的幾行std :: string {aka std :: basic_string <char>}'to'char *'in assignment |

部分代碼:

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]; 

不能轉換 '的std :: string {又名性病:: basic_string的}' 來'char *' 正在賦值|

+0

可能重複[如何將std :: basic \ _string類型轉換爲char類型的數組?](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*

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

請注意:此指針僅對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]; 

逸岸,這裏是一個使用標準C++算法在整個(的std :: string ::比較,而不是STRCMP)重寫。這可能使您更容易專注於算法本身。

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 *',因爲它們不兼容。您需要調用字符串的'c_str()'方法來獲取std :: string管理的'const char *'。 – kfsone

+0

不要讓名字'string'混淆你:'std :: string'是一個類名。 'char foo [] =「hello」;''和'char * foo =「hello」;'是C風格的字符串,而'std :: string foo =「hello」;'是完全不同的野獸。 – kfsone

相關問題