两个数组的交集函数给出不好的结果

时间:2019-02-17 11:02:54

标签: c++ arrays intersection

我编写了此函数,该函数将两个数组(具有各自的长度)作为参数,并返回另一个数组,其中两个数组中的元素相同。但是,相反,它给了我更多数字。

void intersection(int vector1[], int length1, int vector2[], int length2, int vectorResult[], int& resultLength) {
int index = 0;
for (int i = 0; i < length1; i++) {
    for (int j = 0; j < length2; j++) {
        if (vector1[i] == vector2[j]) {
            vectorResult[index] = vector2[j];
            resultLength++;
            index++;
        }
    }

}
}

因此,有了这些向量:

Vector1: [1,3,5,7,9]
Vector2: [9,10,11,12,13,14]
Result: [9]

相反,我得到了:

Vector1: [1,3,5,7,9]
Vector2: [9,10,11,12,13,14]
Result: [9,2,3,4,5,0,0]

1 个答案:

答案 0 :(得分:1)

假设在调用intersection之前对两个数组都进行了排序,

void intersection(int vector1[], int length1, int vector2[], int length2, int vectorResult[], int &resultLength) {
    resultLength = std::distance(vectorResult,
                                 std::set_intersection(vector1, vector1 + length1,
                                                       vector2, vector2 + length2,
                                                       vectorResult));
}