C ++并集,交集,差值

问题描述 投票:0回答:1

所以我正在研究一个代码,以查找两个数组之间的并集,相交和差。我已经完成了“联合和相交”,但我只是想不出区别(A-B),例如A = {1,3,6,9,7,9},B = {2,3, -2,9}我想得到A-B = {1,6,7,0}。

除了iostream,我不想使用任何其他库。

到目前为止,这是我的代码。

/* Prints union of A[] and B[]
   SizeA is the number of elements in A[]
   SizeB is the number of elements in B[] */

cout << "\nUnion of A and B = "; //
i = 0; j = 0;
while (i < SizeA && j < SizeB)
{
    if (A[i] < B[j])
        cout << A[i++] << " ";

    else if (B[j] < A[i])
        cout << B[j++] << " ";

    else
    {
        cout << B[j++] << " ";
        i++;
    }
}
/* Print remaining elements of the larger array */
while (i < SizeA)
    cout << A[i++] << " ";

while (j < SizeB)
    cout << B[j++] << " ";



cout << "\nIntersection of A and B = ";
for (i = 0; i < SizeA; i++) //for loop to calculate the intersection of A and B.
{
    for (j = 0; j < SizeB; j++)
    {
        if (A[i] == B[j])
        {
            cout << A[i] << " ";
        }
    }
}
c++ set difference
1个回答
0
投票

如果可以保存交叉点,则可以仅将A和B的每个元素与该交叉点的元素进行比较。否则,您需要两个for循环:

cout << "\nDifference of A and B = ";
for (i = 0; i < SizeA; i++) //for loop to calculate the intersection of A and B.
{
    bool found = false
    for (j = 0; j < SizeB; j++)
    {
        if (A[i] == B[j])
        {
            found = true;
        }
    }
    if (!found) {
       cout<<A[i]<<" ";
    }
}
for (i = 0; i < SizeB; i++)
{
    bool found = false
    for (j = 0; j < SizeA; j++)
    {
        if (B[i] == A[j])
        {
            found = true;
        }
    }
    if (!found) {
       cout<<B[i]<<" ";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.