C++ std::string {aka std::basic_string<char>}' 到 'char*' 赋值|
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19739079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
std::string {aka std::basic_string<char>}' to 'char*' in assignment|
提问by Bernardo Baalen
tried to open a .cpp in code::blocks. Got few lines of error
试图在 code::blocks 中打开一个 .cpp。有几行错误
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*”|
回答by kfsone
Because they're incompatible. You need to call a member of std::stringwhich 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 的生命周期内有效,或者直到您修改 string 对象为止。
This function returns a const char*so you'll need to change the definition of xfrom char*to `const char*.
此函数返回 a,const char*因此您需要将xfrom的定义更改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). This may make it easier for you to focus on the algorithm itself.
事实上,这是一个重写,它在整个过程中使用标准 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);
}

