gpt4 book ai didi

c++ - std::string {aka std::basic_string }' to ' char*' 在赋值中|

转载 作者:行者123 更新时间:2023-11-28 03:05:53 32 4
gpt4 key购买 nike

试图在 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];

cannot convert 'std::string {aka std::basic_string}' to 'char*' in assignment|

最佳答案

因为它们不相容。您需要调用 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);
}

关于c++ - std::string {aka std::basic_string<char> }' to ' char*' 在赋值中|,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19739079/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com