排序并从C中的int数组中删除重复项 [英] sort and remove duplicates from int array in c

查看:135
本文介绍了排序并从C中的int数组中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C,并且涉及了排序主题.我在其中编写了comp()函数,并使用qsortint的数组进行了排序.现在,对于下一个任务,我需要从阵列中删除重复项.
可以同时分类和删除重复项吗?

I am learning C and came over the topic of sorting. I wrote a comp() function in and used qsort to sort an array of int. Now for the next task I need to remove the duplicates from the array.
Is it possible to sort and remove duplicates at the same time?

#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内置:

Since your numbers are already sorted, removing dupes is easy. In C++, it's even built in as std::unique:

http://en.cppreference.com/w/cpp/algorithm/unique

假设您想自己做,可以按照unique的相同方法来做:

Assuming you want to do it yourself, you can do it the same way unique does it:

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中的int数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆