我是学C的,排序的题目过来了。我写了一个 comp()
函数并使用 qsort
对 int
数组进行排序。现在,对于下一个任务,我需要从数组中删除重复项。
是否可以同时排序和删除重复项?
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int indexes[10] = { 0, 98, 45, 65, 45, 98, 78, 56, 65, 45 };
int comp(const void * elem1, const void * elem2) {
int f = *((int*) elem1);
int s = *((int*) elem2);
if (f > s) {
return 1;
}
if (f < s) {
return -1;
}
return 0;
}
void printIndexArray() {
int i = 0;
for (i = 0; i < 10; i++) {
printf("i is %d\n", indexes[i]);
}
}
int main() {
qsort(indexes, sizeof(indexes) / sizeof(int), sizeof(int), comp);
printIndexArray();
return 0;
}
最佳答案
由于您的号码已经排序,因此删除重复号码很容易。在 C++ 中,它甚至内置为 std::unique
:
http://en.cppreference.com/w/cpp/algorithm/unique
假设你想自己做,你可以像 unique
那样做:
int* unique (int* first, int* last)
{
if (first==last) return last;
int* result = first;
while (++first != last)
{
if (!(*result == *first))
*(++result)=*first;
}
return ++result;
}
关于c - 排序并从 c 中的 int 数组中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18924792/