set_intersection of vector<pair> 元素

rmv*_*v24 0 c++ vector std-pair

我试图查看set_intersectionC++ 中的函数是如何工作的,对于 a 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;
}

Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

Intersection :

1 1

1 3

2 1

3 2
Run Code Online (Sandbox Code Playgroud)

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

Intersection :

1 1

1 3

3 2
Run Code Online (Sandbox Code Playgroud)

我不确定在这段非常简单的代码中我是否在某处出错,因此我很感激这方面的一些帮助。

cig*_*ien 5

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

因此就其set_intersection而言,既不{2,1}也不{2,3}小于另一个,因此它们被认为是等效的。

set_intersection当它看到两个范围中的公共元素时,将添加第一个范围中的元素,因此您将获得{2,1}输出。

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