c++ - 合并排序字符串
问题描述
我正在尝试使用归并排序,对字符串中的所有字符进行排序。但我总是遇到一些编译问题。具体来说,我在以下行遇到问题:[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 >' 的表达式
解决方案
s[i]
is not a string
it's achar
并且char
没有任何成员函数。
而不是 :
if (s[i1].compare(s[i2]) < 0)
你应该尝试类似的东西:
if (s[i1] < s[i2])
推荐阅读
- tabs - 是否可以在点击打开时自动运行 iTerm2 脚本
- java - POI excel跳过第一行
- python - 根据键值合并两个字典列表
- architecture - 使用rabbitmq队列处理微服务之间的实时数据同步
- orbeon - Orbeon Forms - 处理服务响应
- sql - 如果我使用 PostgreSQL,我是否也需要服务器?喜欢 AWS RDS?
- python - 如果程序创建了 excel 文件,则 Pandas read_excel 为具有简单公式的单元格返回 nan
- python - Python Tkinter 弹出框
- android - 如何在 Robolectric 4.3.1 上阴影 Kotlin 伴侣对象?
- javascript - 你如何解决节点中的这个循环依赖问题