C语言 Qsort函数对数组中的单词进行唯一排序



我试图建立一个qsort函数,将排序的词在我的指针数组**allwords,唯一。但是我哪里出错了,我做错了什么?(对C很陌生)

static int intcmp(const void *a, const void *b) {
const int *left = a;
const int *right = b;
return *left - *right;
}

如果指针指向字符串,而您需要比较字符串,那么比较函数将看起来像

static int intcmp(const void *a, const void *b) {
const char *left = *( const char ** )a;
const char *right = *( const char ** )b;
return strcmp( left, right );
}

注意,qsort传递给比较函数的是指向已排序数组元素的指针。在您的例子中,元素具有类型char *,那么指向它们的指针将具有类型char **,并分配给类型const void *的指针。所以在比较函数中你需要做一个"反"从const void *const char **的指针强制转换。

这是一个示范程序。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int cmp( const void *a, const void *b ) 
{
const char *left  = *( const char ** )a;
const char *right = *( const char ** )b;
return strcmp( left, right );
}
int main( void )
{
char *words[] =
{
"The",  "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"
};
const size_t N = sizeof( words ) / sizeof( *words );
char **allwords = words;
qsort( allwords, N, sizeof( *allwords ), cmp );
for (size_t i = 0; i < N; i++)
{
puts( allwords[i] );
}
}

程序输出为

The
brown
dog
fox
jumps
lazy
over
quick
the

您应该考虑使用std::string和vector来代替原始指针数组。你可以写得更简单、更安全。

#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
vector<string> v{ "ghi", "def", "abc", "def" };
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
for (auto s : v) {
printf("%sn", s.c_str());
}
}

的输出是排序的且唯一的

abc
def
ghi

最新更新