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

时间:2018-01-23 04:13:44

标签: c++ intersection

我能够编写一个打印出两个数组交集的函数。但是,我试图获得交叉点成员的价值。

如果我们的最终交叉点为{6, 12},我应该返回2作为值,因为我有2个成员。我的回报值是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;
}

2 个答案:

答案 0 :(得分:1)

使用std::vector代替数组。

# 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

答案 1 :(得分:1)

使用算法库,特别是std::set_intersection

以下是上面链接的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();
}