[英]std::string {aka std::basic_string<char>}' to 'char*' in assignment|
tried to open a .cpp in code::blocks. 试图在code :: blocks中打开一个.cpp。 Got few lines of error
得到的错误很少
Partial code : 部分代码:
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);
}
}
I recieve this error in line 我收到了这个错误
x = List[(Left+Right)/2];
cannot convert 'std::string {aka std::basic_string}' to 'char*' in assignment|
无法在赋值中将'std :: string {aka std :: basic_string}'转换为'char *'
Because they're incompatible. 因为它们不相容。 You need to call a member of
std::string
which returns a const char*
. 您需要调用
std::string
的成员,该成员返回一个const char*
。
x = List[(Left+Right)/2].c_str();
Be aware: this pointer is only valid for the life time of the std::string or until you modify the string object. 请注意:此指针仅对std :: string的生命周期有效,或者直到您修改字符串对象为止。
This function returns a const char*
so you'll need to change the definition of x
from char*
to `const char*. 此函数返回一个
const char*
因此您需要将x
的定义从char*
更改为`const char *。
const char* x;
or better still, remove that line, and combine the two 或者更好的是,删除该行,并将两者结合起来
void QSort(string List[], int Left, int Right)
{
string TEMP;
int i = Left;
int j = Right;
const char* x = List[(Left+Right)/2];
Infact, here's a rewrite that uses standard C++ algorithms throughout (std::string::compare instead of strcmp). 事实上,这里是一个使用标准C ++算法的重写(std :: string :: compare而不是strcmp)。 This may make it easier for you to focus on the algorithm itself.
这可能使您更容易专注于算法本身。
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.