Search code examples
c++vectorstd-pair

set_intersection of vector<pair> elements


I was trying to see how the set_intersection function in C++ works, for a vector<pair>s and wrote this piece of code:

#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;
}

I get the following output:

Intersection :

1 1

1 3

2 1

3 2

But, only three of the pairs are common between the two vectors, and so I believe my output should be:

Intersection :

1 1

1 3

3 2

I'm not sure if I'm going wrong somewhere in this really simple piece of code, and hence I'd appreciate some help with this.


Solution

  • Your output is perfectly fine. The issue is your comparator comp only considers the .first member of each pair when deciding the ordering.

    So as far as set_intersection is concerned, neither {2,1}, nor {2,3} is less than the other, and so they are considered to be equivalent.

    set_intersection will add the element from the first range when it sees a common element in both ranges, and so you get {2,1} in the output.

    If you want both elements of the pairs to be used when determining equivalence, you can modify your comparator. Even better, don't pass a custom comparator at all, since the default ordering of std::pair will do the right thing here.