[英]Error cannot convert 'std::string {aka std::basic_string<char>}' to 'char' in assignment - C++
[英]std::string {aka std::basic_string<char>}' to 'char*' in assignment|
試圖在code :: blocks中打開一個.cpp。 得到的錯誤很少
部分代碼:
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 {aka std :: basic_string}'轉換為'char *'
因為它們不相容。 您需要調用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 :: compare而不是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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.