【问题标题】:Merge sorting a string合并排序字符串
【发布时间】:2020-01-28 06:53:06
【问题描述】:

我正在尝试使用归并排序,对字符串中的所有字符进行排序。但我总是遇到一些编译问题。具体来说,我在以下几行遇到问题:[if (s[i1].compare(s[i2])

void mergeSort(string &s, int from, int to)
{
    if (from == to)
    {
        return;
    }
    int mid = (from + to) / 2;
    mergeSort(s, from, mid);
    mergeSort(s, mid + 1, to);
    merge(s, from, mid, to);

}

 void merge(string &s, int from, int mid, int to)
 {
    int n = to - from + 1;
    vector<string> b(n); // merge both halves into a temporary vector b
    int i1 = from;  
    int i2 = mid + 1; 
    int j = 0;


    while (i1 <= mid && i2 <= to)
    {
        if (s[i1].compare(s[i2]) < 0)
        {
            b[j] = s[i1];
            i1++;
        }
        else
        {
            b[j] = s[i2];
            i2++;
        }
        j++;
    }
    // copy any remaining entries of the first half
    while (i1 <= mid)
    {
        b[j] = s[i1];
        i1++;
        j++;
    }

    // copy any remaining entries of the second half
    while (i2 <= to)
    {
        b[j] = s[i2];
        i2++;
        j++;
    }
    // copy back from the temporary array
    for (j = 0; j < n; j++)
    {
        s[from + j] = b[j];
    }
 } 

int main(){
string str = "cdebfag"
if (str.length() >= 2 )
mergeSort(str, 0, str.length() - 1);

//print sorted
cout << str << endl;

return 0;

}

错误是:

在 '(& s)->std::__cxx11::basic_string::operator' 中请求成员 'compare',它是非类类型 '__gnu_cxx::__alloc_traits, char>::value_type' {aka '字符'}

'std::vector >' 类型的表达式对'std::__cxx11::string&' {aka 'std::__cxx11::basic_string&'} 类型的引用的初始化无效

【问题讨论】:

    标签: c++ arrays string sorting mergesort


    【解决方案1】:

    除了 Sid 的回答之外,您还应该使用 vector&lt;char&gt; b 而不是 vector&lt;string&gt; b

    【讨论】:

      【解决方案2】:

      s[i] 不是string 它是char 并且char 没有任何成员函数。

      而不是:

      if (s[i1].compare(s[i2]) < 0)
      

      您应该尝试类似的方法:

      if (s[i1] < s[i2])
      

      【讨论】:

        猜你喜欢
        • 2012-01-17
        • 2012-11-29
        • 2012-05-01
        • 1970-01-01
        • 2013-03-31
        • 1970-01-01
        • 1970-01-01
        • 2019-03-13
        • 1970-01-01
        相关资源
        最近更新 更多