set_intersection 个矢量<pair> 个元素

set_intersection of vector<pair> elements

我试图了解 C++ 中的 set_intersection 函数是如何工作的 vector<pair>s 并编写了这段代码:

#include <iostream>
#include <vector>
#include <bits/stdc++.h>

using namespace std;

bool comp(pair<int, int> &a, pair<int, int> &b )
{
    return a.first < b.first; 
}

int main()
{
    vector<pair<int, int>> v1;
    vector<pair<int, int>> v2;
    vector<pair<int, int>> res;
    
    v1.push_back(make_pair(1,1)); 
    v1.push_back(make_pair(2,1));
    v1.push_back(make_pair(3,2)); 
    v1.push_back(make_pair(2,2));
    v1.push_back(make_pair(1,3)); 
    
    
    v2.push_back(make_pair(1,1)); //same
    v2.push_back(make_pair(2,3));
    v2.push_back(make_pair(3,2)); //same
    v2.push_back(make_pair(4,2));
    v2.push_back(make_pair(1,3)); //same
    
    sort(v1.begin(), v1.end(), comp);
    sort(v2.begin(), v2.end(), comp);
    
    set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), inserter(res, res.begin()), comp);
    
    cout << "Intersection : " << endl;
    for(auto it = 0; it < res.size(); it++)
        cout << res[it].first << " " << res[it].second << endl;
}

我得到以下输出:

Intersection :

1 1

1 3

2 1

3 2

但是,两个向量之间只有三对是公共的,所以我相信我的输出应该是:

Intersection :

1 1

1 3

3 2

我不确定我是否在这段非常简单的代码中哪里出错了,因此我希望能得到一些帮助。

你的输出完全没问题。问题是您的比较器 comp 在决定​​排序时仅考虑每对的 .first 成员。

所以就set_intersection而言,{2,1}{2,3}都不小于对方,所以认为它们是等价的。

set_intersection 会在发现两个范围中的共同元素时添加第一个范围中的元素,因此您在输出中得到 {2,1}

如果您希望在确定等价性时使用对的两个元素,您可以修改比较器。更好的是,根本不要传递自定义比较器,因为 std::pair 的默认顺序会在这里做正确的事情。