c - 排序并从 c 中的 int 数组中删除重复项

标签 c arrays sorting

我是学C的,排序的题目过来了。我写了一个 comp() 函数并使用 qsortint 数组进行排序。现在,对于下一个任务,我需要从数组中删除重复项。
是否可以同时排序和删除重复项?

#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/

相关文章:

c - atoi、atol 和 stoi 分别代表什么?

android - 将字符串数组转换为整数数组

arrays - 可以在 shell 中读取命令用于将字符串分配给数组并重置默认数组

linux - 对字段中的 $ 值(以逗号作为千位分隔符的美国格式数字)进行排序

c - 需要 API 完整性自动测试帮助

c - 程序查找字符串中最长的单词

php - 按字母顺序排列数组

javascript - 使用 JavaScript 按字母顺序排序丹麦语?

c++ - 在 Windows 内核设备驱动程序中使用 fprintf

php - 如何在不知道索引值名称的情况下打印数组的值