I want to perform a multi-set intersection using C

2019-09-20 03:50发布

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.

2条回答
Bombasti
2楼-- · 2019-09-20 04:41

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!

查看更多
3楼-- · 2019-09-20 04:44

set_intersection actually performs intersection for multisets, too. I assume your call of set_intersection was wrong. There are few requirements you must meet, described in reference, for example:

The resulting range cannot overlap with either of the input ranges.

However, see the following code:

#include <iostream>
#include <iterator> // inserter
#include <algorithm> // set_intersection
#include <set> // multiset

int main() {
    std::multiset<int> set1 = { 1,1,2,2,3,3,4,4,5,5,6,6 };
    std::multiset<int> set2 = { 4,4,5,5,6,6,7,7,8,8,9,9 };
    std::multiset<int> intersection;
    std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(intersection, intersection.begin()));

    // prints: 4 4 5 5 6 6 
    for(int elem : intersection) {
        std::cout << elem << ' ';
    } 
}
查看更多
登录 后发表回答