简体   繁体   English

如何计算两个数组的交集值?

[英]how to compute value of intersection of two arrays?

I was able to write a function that prints out the intersection of two arrays. 我能够编写一个打印出两个数组的交集的函数。 However, I am trying to obtain the value of the members of the intersection. 但是,我试图获得交叉口成员的价值。

If our final intersection is {6, 12} I should return 2 as the value because I have 2 members. 如果我们的最终交集为{6, 12}我应该返回2作为值,因为我有2个成员。 My return value is 1 and I don't know what I am doing wrong. 我的返回值为1,我不知道自己在做什么错。

int main()
{
    int data1[] = { 3, 6, 9, 12};
    int data2[] = { 2, 4, 6, 8, 10, 12 };
    int result[] = {};
    size_t length1 = sizeof(data1)/sizeof(int);
    size_t length2 = sizeof(data2)/sizeof(int);
    size_t resultMax= 0;
    int i =0;
    int j =0;

    while (i < length1 && j < length2)
    {
        if (data1[i] < data2[j])
        {
            i++;
        }
        else if (data2[j] < data1[i])
        {
            j++;
        }
        else if (data1[i] == data2[j])
        {
            result[i] = data1[i];
            cout << "valor : " << result[i] << endl; // output is 6 and 12
            i++;
            j++;
            resultMax = sizeof(result[i])/sizeof(int);
        }
    }

    cout << "Final Size: "<< resultMax; //output is 0
    return resultMax;
}

Use std::vector instead of array. 使用std :: vector而不是array。

# include<iostream>
# include<vector>
using namespace std;

int main()
{
    vector<int> data1 = { 3, 6, 9, 12}, data2 = { 2, 4, 6, 8, 10, 12 }, result;
    int i = 0, j = 0, length1 = data1.size(), length2 = data2.size();
    while (i < length1 && j < length2)
    {
        if (data1[i] < data2[j])
            i++;
        else if (data2[j] < data1[i])
            j++;
        else if (data1[i] == data2[j])
        {
            result.push_back(data1[i]);
            cout << "valor : " << data1[i] << endl;
            i++;
            j++;
        }
    }
    cout << "Final Size: "<< result.size(); 
    return 0;
}

Live Code 现场代码

Use the algorithm library, specifically std::set_intersection . 使用算法库,特别是std :: set_intersection

The following is a slightly adapted example from the above linked cppreference page: 以下是来自上面链接的cppreference页面的稍微改编的示例:

int main()
{
    std::vector<int> v1{3, 6, 9, 12};
    std::vector<int> v2{2, 4, 6, 8, 10, 12 };
    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());

    std::vector<int> v_intersection;

    std::set_intersection(v1.begin(), v1.end(),
                          v2.begin(), v2.end(),
                          std::back_inserter(v_intersection));

    std::cout << "Final Size: "<< v_intersection.size();
}

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

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