合并排序字符串

问题描述 投票:0回答:2

我正在尝试使用合并排序来对字符串中的所有字符进行排序。但是我总是遇到一些编译问题。具体来说,我在以下方面遇到问题:[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'炭'}

类型'std :: __ cxx11 :: string&'的引用的无效初始化{aka'std :: __ cxx11 :: basic_string&'}来自类型'std :: vector的表达式”

c++ arrays string sorting mergesort
2个回答
2
投票

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

而不是:

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

您应该尝试类似:

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

1
投票

除了Sid的答案,您还应该输入vector<char> b而不是vector<string> b

© www.soinside.com 2019 - 2024. All rights reserved.