首页 > 解决方案 > 合并排序字符串

问题描述

我正在尝试使用归并排序,对字符串中的所有字符进行排序。但我总是遇到一些编译问题。具体来说,我在以下行遇到问题:[if (s[i1].compare(s[i2]) < 0)] 和 [s[from + j] = b[j];]。请问有什么帮助吗?

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 'char' }

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

标签: c++arraysstringsortingmergesort

解决方案


s[i]is not a stringit's achar并且char没有任何成员函数。

而不是 :

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

你应该尝试类似的东西:

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

推荐阅读