我试着看看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我不确定我是否在这段非常简单的代码中出错了,因此我希望在这方面能得到一些帮助。
发布于 2020-10-26 22:56:36
你的输出是非常好的。问题是您的比较器comp在决定排序时只考虑每对中的.first成员。
因此,就set_intersection而言,{2,1}和{2,3}都不是小于另一个,因此它们被认为是等价的。
当set_intersection在两个范围中看到一个公共元素时,它将添加第一个范围中的元素,因此您将在输出中获得{2,1}。
如果您希望在确定等价性时使用对的两个元素,则可以修改比较器。更好的是,根本不要传递自定义比较器,因为std::pair的默认排序在这里会做正确的事情。
https://stackoverflow.com/questions/64539485
复制相似问题