Search code examples
c++setmultisetset-intersection

I want to perform a multi-set intersection using C++


I am using std::set<int> and multi-set classes std::multiset<int> to perform some set operations - union, intersection etc. The problem is that I have to perform intersection between two multi-sets such that I also get the duplicate values. The intersection works fine when I use it with simple sets (not multi-sets) e.g.

Set1={1,2,3,4,5,6}
Set2={4,5,6,7,8,9}
then the
std::set_intersection give me a correct result which is {4,5,6}

However, if I have a multiset

multi-set1{1,1,2,2,3,3,4,4,5,5,6,6}
multi-set2{4,4,5,5,6,6,7,7,8,8,9,9}

and I again use the std::set_intersection it again gives me the result {4,5,6}

which is not correct, because the actual intersection is {4,4,5,5,6,6}

Although I am using a multi-set to hold the results of intersection, still I get the wrong answer.

Can anyone tell me how can I solve this issue.


Solution

  • Would you please post your code to check if there are mistakes? I have coded an intersection example like the code below and it works.

    multiset<int> ms1;
    ms1.insert(1);
    ms1.insert(1);
    ms1.insert(1);
    ms1.insert(2);
    ms1.insert(3);
    
    multiset<int> ms2;
    ms2.insert(1);
    ms2.insert(1);
    ms2.insert(2);
    ms2.insert(2);
    ms2.insert(4);
    
    vector<int> v(10);
    set_intersection( ms1.begin(), ms1.end(), ms2.begin(), ms2.end(), v.begin() );
    

    the result is 1, 1, 2. which is correct!