如何从数组中排除元素?

时间:2019-05-11 08:40:52

标签: c arrays

我有2个数组a1 = {1,2,3,4,5,6,7.....}a2 = {1,3,5,7} 如果我必须从a2中排除a1的元素并打印a1,什么是最好的方法?

2 个答案:

答案 0 :(得分:1)

当解释为“如果a2中不存在,则从a1打印”:

#include <stdio.h>

int main(void) {
    int a1[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int a2[] = {1, 3, 5, 7};
    printf("elements of a1 not present in a2:");
    for (int i = 0; i < sizeof a1 / sizeof *a1; i++) {
        int found = 0;
        for (int j = 0; j < sizeof a2 / sizeof *a2; j++) {
            if (a1[i] == a2[j]) { found = 1; break; }
        }
        if (!found) printf(" %d", a1[i]);
    }
    puts("");
    return 0;
}

请参见code running on ideone

答案 1 :(得分:1)

示例函数,该函数从数组中删除所有具有特定值的元素。此示例适用于类型int,但是更改其他任何类型

都很容易
size_t remove_element(int *arr, size_t size, int element)
{
    for(size_t index = 0; index < size; )
    {
        if(arr[index] == element)
        {
            memmove(arr + index, arr + index + 1, (size - index - 1) * sizeof(*arr));
            size --;
            continue;
        }
        index++;
    }
    return size;
}

int main()
{

    int h[] = {4,6,8,9,2,3,0,1,2,5,6,9,0};
    size_t size = sizeof(h) / sizeof(h[0]), newsize = remove_element(h, size, 0);

    printf("Size Before:%zu New size %zu\n", size, newsize);


    for(size_t index = 0; index < newsize; index++)
    {
        printf("h[%zu] = %d\n", index, h[index]);
    }

    return 0;
}

并删除另一个数组中的元素

size_t remove_elements(int *arr, size_t arrsize, const int *elements, size_t elemsize)
{
    for(size_t index = 0; index < elemsize; index++)
    {
        arrsize = remove_element(arr, arrsize, elements[index])
    }
    return arrsize;
}

尝试一下: https://onlinegdb.com/ryRJOGNnN