std::string {aka std::basic_string<char>}' 到 'char*' in assignment|
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*" 在作业中|
因为它们不兼容。您需要调用返回const char*
的 std::string
的成员。
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);
}
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL