比较 qsort 中的字符串
Comparing strings in qsort
每当我在 qsort 中比较字符串时,顺序完全错误。比如输入是
45 4 9 22 2
但我的输出是
22 45 4 9 2
这是我的比较函数
int cmpString(const void *a, const void *b) {
const Node *a1 = *(const Node **)a;
const Node *b1 = *(const Node **)b;
return a1->s.c_str() - b1->s.c_str();
}
不要告诉我使用 sort(),我做不到这个作业
这一行是您代码的主要问题。
return a1->s.c_str() - b1->s.c_str();
这背后的原因是你在这里减去两个指针,这不是比较器在这种情况下应该做的。比较器根据内容进行比较。
相反,试试这个:
int length1 = a1->s.size();
int length2 = b1->s.size();
for (int i = 0; i < min(length1, length2); i++) {
if (a1->s[i] != b1->s[i]) { // if characters are not same, return difference of their ASCII values.
return a1->s[i] - b1->s[i];
}
}
return length1 - length2; // if they are same till now, then shorter string should appear first. That's why it is required.
建议:
如果您使用 C++ 进行编码,请使用 STL。 <algorithm>
给出了一个很好的函数 sort()
,它允许你在不使用 void *
的情况下做同样的事情
更新:
根据user4581301的正确建议,您可以直接使用std::string::compare。
像这样:
return (a1->s).compare(b1->s);
每当我在 qsort 中比较字符串时,顺序完全错误。比如输入是
45 4 9 22 2
但我的输出是
22 45 4 9 2
这是我的比较函数
int cmpString(const void *a, const void *b) {
const Node *a1 = *(const Node **)a;
const Node *b1 = *(const Node **)b;
return a1->s.c_str() - b1->s.c_str();
}
不要告诉我使用 sort(),我做不到这个作业
这一行是您代码的主要问题。
return a1->s.c_str() - b1->s.c_str();
这背后的原因是你在这里减去两个指针,这不是比较器在这种情况下应该做的。比较器根据内容进行比较。
相反,试试这个:
int length1 = a1->s.size();
int length2 = b1->s.size();
for (int i = 0; i < min(length1, length2); i++) {
if (a1->s[i] != b1->s[i]) { // if characters are not same, return difference of their ASCII values.
return a1->s[i] - b1->s[i];
}
}
return length1 - length2; // if they are same till now, then shorter string should appear first. That's why it is required.
建议:
如果您使用 C++ 进行编码,请使用 STL。 <algorithm>
给出了一个很好的函数 sort()
,它允许你在不使用 void *
更新:
根据user4581301的正确建议,您可以直接使用std::string::compare。
像这样:
return (a1->s).compare(b1->s);