C:仅在2个数组中打印不常见的元素 [英] C: Print only not common elements in 2 arrays

查看:101
本文介绍了C:仅在2个数组中打印不常见的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些要修改的C代码真的很简单.

I have some C code I want to modify really simple.

假设我有两个这样的数组

Let's say I have two arrays like this

   int v1[5] = {1, 3, 7, 13, 10};
   int v2[2] = {1, 10};

我想打印一些不常见的元素(差异):

And I would like to print the not common elements (difference) like:

3, 7, 13

这是我的尝试,还不够:

Here is my attempt which is not enough yet:

#include <stdio.h>

int main()
{
    int v1[5] = { 1, 3, 7, 13, 10 };
    int v2[2] = { 1, 10 };

    for (int i = 0; i < sizeof(v1) / (sizeof * v1); i++) {
        for (int j = 0; j < sizeof(v2) / (sizeof * v2); j++) {
            if (v1[i] != v2[j]) {
                printf("%d ", v1[i]);
                break;
            } else {
                break;
            }
        }
    }

    return 0;
}

两个数组总是很短(最多6个元素). Thery没有命令,我不应该修改它们.每个元素中的元素都是唯一的,即每个数字在每个数组中只能出现1次. v2仅包含来自v1的元素的子集. 实现这一目标的最有效方法是什么?

The two arrays will be always really short (max 6 elements). Thery are not ordered and I should not modify them. The elements in each of them are unique, that is each number can only appear 1 time in each array. v2 will only contains a subset of element from v1. What would be the most efficient way to achieve this?

推荐答案

您可以首先获取任何数组,然后逐个元素对其进行迭代,并通过嵌套的for循环查找该元素是否也位于第二个数组中,并放置一个if条件在内部for循环中,将公共元素存储在另一个数组中,然后将两个数组与该数组一一进行比较,然后将不常见的元素放入另一个数组中.

You could start by taking any array and iterating it element by element and finding if that element is in second array too by a nested for loop and putting an if condition in the inner for loop and storing the common element in another array and then comparing both of the array one by one with that array and putting uncommon element in another array.

赞:

int a[min(l1,l2)], b[l], x = 0, k = 0, flag = 1;
for(int i=0; i<l1; i++){
for(int j=0; j<l2; j++){
    if(v1[i]==v2[j]){
        a[k] = v1[i];
        k++;
    }
}
}
for(int i=0; i<l1; i++){
flag = 1;
for(int j=0; j<k; j++){
    if(v1[i] == a[j]){
      flag = 0;
      break;
    }
}
if(flag==1){
    b[x] = v1[i];
    x++;
}
}

for(int i=0; i<l2; i++){
flag = 1;
for(int j=0; j<k; j++){
    if(v2[i] == a[j]){
      flag = 0;
      break;
    }
}
if(flag==1){
    b[x] = v2[i];
    x++;
}
}

之后,您可以打印阵列.

Afterwards you can print the array.

这篇关于C:仅在2个数组中打印不常见的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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