C ++ set_difference方法无法按预期工作

时间:2018-06-05 01:44:30

标签: c++ stl set-difference

我试图找出这两组的差异{1,2,3,4,5,6}和 {1,3,6,4,1,2}。 missing向量应仅包含{5},但它包含{2,4,5}。我在这做错了什么?

#include <set>
#include <vector>
#include <iostream>
using namespace std;
int solution(vector<int> &A) {
    vector<int> missing;
    vector<int> range(A.size());
    for(int i=1; i<= A.size(); i++) range[i-1] = i;

    set_difference(range.begin(), range.end(), A.begin(), A.end(), std::inserter(missing, missing.end()));
    return missing[0]; // Missing contains 2,4,5 where as it should had contain just 5
}

int main(){
    vector<int> A = {1, 3, 6, 4, 1, 2};
    cout << solution(A);
   return 0;
}

1 个答案:

答案 0 :(得分:0)

std :: inserter 方法的第二个参数应该是 missing.begin()而不是 missing.end()

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

set_difference(range.begin(), range.end(), A.begin(), A.end(), std::inserter(missing, missing.begin()));