一个类项目涉及对字符串数组进行排序,每个字符串包含相同数量的列,如下所示:
Cartwright Wendy 93 Williamson Mark 81 Thompson Mark 100 Anderson John 76 Turner Dennis 56
The program accepts a command-line argument for which column to sort on, and should print out the sorted strings unmodified.
I would like to use strtok to break up copies of each string into columns, and make structs for each line like this:
struct line {
char * line;
char column_to_sort_on[MAX_COLUMN];
}
我的问题出在 qsort 作为参数的比较函数指针上。如果我理解正确的话,比较函数必须采用两个 const void 指针指向要排序的项目,并返回一个 int。这意味着我无法将指向结构的指针传递给比较函数,因为这不是 qsort 将要排序的内容。我无法传入列号以对比较函数进行排序,因为它只能采用两个参数。我怎样才能解决这个问题,根据特定的列对这些字符串进行排序?
编辑:如果我真的想要,排序仅限于 qsort 或我自己的排序。给个选择,我选qsort。 :)
编辑#2:共识似乎是要么使用全局变量作为列号,要么只使用 qsort 对结构数组进行排序。我没想到只是对结构进行排序,然后使用其中的指针打印出原始字符串。我想这就是我要做的。感谢大家的帮助!
最佳答案
您可以像这样传递结构:
struct line {
char * line;
char column_to_sort_on[MAX_COLUMN];
}
...
line* Lines[max_lines]; // here you store the structs
int
cmp_lines( const void *elem1, const void *elem2 )
{
line* line1 = *(line**)elem1;
line* line2 = *(line**)elem2;
// do the comparisons
}
qsort(Lines, max_lines, sizeof(line*), cmp_lines);
关于c++ - Qsort 基于 c 字符串中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1449299/