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

爷,独闯天下 提交于 2019-12-25 18:34:55

问题


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.


回答1:


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!




回答2:


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


来源:https://stackoverflow.com/questions/41782233/i-want-to-perform-a-multi-set-intersection-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!