繁体   English   中英

std :: string {aka std :: basic_string <char> 分配给&#39;&#39;&#39;char *&#39;

[英]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 *'

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM