数组中保留的 2 个集合的差异 - C++

Difference of 2 sets retained in arrays - C++

考虑在两个数组中保留两个集合。求两个集合的并集、交集和差集(相对补集)。

我设法解决了并集和交集,但不同点让我很难过。有什么提示吗?如果可能的话,尽量保持简单,没有功能或更复杂的方面,因为我是初学者,我还有很多东西要学。

提前致谢!

#include <iostream>

using namespace std;


int main()
{
int v1[100], v2[100], u[200], intersection[100], d[100];
unsigned int v1_length, v2_length, i, j, OK = 0, union_length;

cout << "Enter the number of elements of the first array:" << " ";
cin >> v1_length;

cout << "Enter the elements of the first array:" << '\n';

for (i = 0; i < v1_length; i++)
    cin >> v1[i];

cout << "Enter the number of elements of the second array:" << " ";
cin >> v2_length;

cout << "Enter the elements of the second array:" << '\n';

for (i = 0; i < v2_length; i++)
    cin >> v2[i];


//Union

union_length = v1_length;

for (i = 0; i < v1_length; i++)
    u[i] = v1[i];

for (i = 0; i < v2_length; i++)
{
    int ok = 0;
    for (j = 0; !ok && j < v1_length; j++)
        if (v1[j] == v2[i])
            ok = 1;

    if (!ok)
    {
        u[union_length] = v2[i];
        union_length++;
    }
}

cout << "The union of the two sets contained in the arrays is: ";

for (i = 0; i < union_length; i++)
    cout << u[i] << " ";

cout << '\n';


//Intersection

unsigned int k = 0;

cout << "The intersection of the two sets contained in the arrays is: ";

for (i = 0; i < v1_length; i++)
    for (j = 0; j < v2_length; j++)
        if (v1[i] == v2[j])
        {
            intersection[k] = v1[i];
            k++;
        }

for (i = 0; i < k; i++)
    cout << intersection[i] << " ";

cout << '\n';


//Difference

unsigned int l = 0, OK2 = 0;

cout << "The difference of the two sets contained in the arrays is: ";

for (i = 0; i < v1_length; i++)
{
    for (j = 0; j < v2_length; j++)
    {
        if (v1[i] == v2[j])
            OK2 = 1;
        if (!OK2)
        {
            d[l] = v1[i];
            l++;
        }
    }
}

for (i = 0; i < l; i++)
    cout << d[i] << " ";

cout << '\n';

return 0; 
}

你走对了!

你做错了几件事。您可以尝试以下修复方法:

  1. 每个内循环仅将 OK2 设置为 0 一次
  2. 在内部循环结束时将 OK2 重置为 0
  3. 只在内部循环完成后插入d

作为优化,在将 OK2 设置为 1 后考虑 break外环指向的当前值。

看来十字路口是最好的起点。您希望只出现在两个数组之一中的项目,对吗?

因此,对于内部循环,您需要比较所有元素。然后,如果未找到匹配项,则您有一个唯一元素。

您需要将大括号{} 添加到for 循环中。我知道花括号有时会让人分心,但随着时间的推移,您可能会发现几乎总是包含它们以避免混淆会更安全。

for (i = 0; i < v1_length; i++)
    for (j = 0; j < v2_length; j++) {
        if (v1[i] == v2[j]){
            break; // this item is not unique
        } else if(j == v2_length - 1){
            d[l] = v1[i];  // This is the unique one, add it to the answer array
            l++;
        }

    }

for (i = 0; i < l; i++)
    cout << intersection[l] << " ";

cout << '\n';