std::string {aka std::basic_string<char>}' 到 'char*' in assignment|

std::string {aka std::basic_string<char>}' to 'char*' in assignment|

本文关键字:std string char in assignment lt basic aka gt      更新时间:2023-10-16

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