fei*_*ght 1 c++ arrays sorting char data-structures
我有一个结构数组,我跟踪在给定文本中看到每个唯一单词的次数:
struct List {
char word[20];
int repeat;
};
Run Code Online (Sandbox Code Playgroud)
现在我需要对此进行排序:
as 6
a 1
appetite 1
angry 1
are 2
and 4
...
Run Code Online (Sandbox Code Playgroud)
对此:
a 1
as 6
and 4
are 2
angry 1
appetite 1
...
Run Code Online (Sandbox Code Playgroud)
(按字母顺序,我的意思是仅用第一个字母表示)到目前为止,我已经想出了这个:
for (i = 0; i < length - 1; i++) {
min_pos = i;
for (j = i + 1; j < length; j++) // find min
if (array[j].word[0] < array[min_pos].word[0]) {
min_pos = j;
}
swap = array[min_pos]; // swap
array[min_pos] = array[i];
array[i] = swap;
}
Run Code Online (Sandbox Code Playgroud)
这段代码非常适合按字母顺序排序,但我无法编写正确的代码来按字母顺序和长度排序.
制作比较器功能.
添加operator<
到您的List
:
bool operator<(const List &lhs) const {
if(word[0] != lhs.word[0]) {
return word[0] < lhs.word[0];
}
return strlen(word) < strlen(lhs.word);
}
Run Code Online (Sandbox Code Playgroud)
现在使用此运算符进行排序,使用您喜欢的任何算法.