繁体   English   中英

C++并、交、差

[英]C++ Union , Intersection , Difference

所以我正在编写一个代码来查找两个数组之间的联合、交集和差异。 我已经完成了联合和交集,但我无法弄清楚差异(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] << " ";
        }
    }
}

这是非常糟糕的做法,因为它不通用,不使用干净的函数并使用普通的旧数组,但我认为您是初学者并且必须以这种方式进行

#include <iostream>

int main()
{
    int A [] ={1,3,6,9,7}, Asz =  5, B [] ={2,3,-2,9}, Bsz =  4;
    std::cout << "\nThe difference is {";
    for( int i = 0; i < Asz; ++i){
        int temp = A[i];
        bool notFound = true;
        for(int j = 0; j < Bsz; ++j){
            if(temp == B[j]) notFound = false;
        }
        if(notFound)
        {
            if(i < Asz - 1) std::cout << temp << ", ";
            else std::cout << temp ;
        }
    }
    std::cout << "}";
}

我喜欢的方式

#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
    std::vector<int> A = {1,3,6,9,7, 0} , B={2,3,-2,9}, C;

    std::sort(A.begin(), A.end());
    std::sort(B.begin(), B.end());

    std::set_difference(A.cbegin(), A.cend(), B.cbegin(), B.cend(), std::back_inserter(C), std::less<int>{});

    for(auto const & el : C)
        std::cout << el << ", ";
}

如果您可以保存交集,则只需根据交集的元素检查 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]<<" ";
    }
}

编辑:没关系,我把差异的定义弄错了(以为是 (AB) + (BA)),所以只需要第一个 for 循环,保存交集没有意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM