I want to perform a union
operation between two multisets
.
However, at the moment I have been able to figure out only to store the output of the operation into a std::vector
, and then I have to convert a vector to a multiset.
This conversion from my tests is very expensive and I would like to avoid that because I need the output as a multiset.
How can I achieve this?
Code:
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
int main () {
multiset<int> m, p;
m.insert(4);
m.insert(4);
m.insert(2);
m.insert(1);
m.insert(7);
p.insert(2);
p.insert(2);
p.insert(2);
p.insert(1);
p.insert(5);
vector<int> v;
set_union(m.begin(), m.end(), p.begin(), p.end(), back_inserter(v));
multiset<int> result(v.begin(), v.end());
multiset<int>::iterator it;
for (it=result.begin(); it!=result.end(); it++)
cout << *it << " ";
return 0;
}
The output is 1 2 2 2 4 4 5 7
as expected.
You need an std::insert_iterator
. It works like std::back_inserter
, but just inserts instead of inserting at the back. You can create one by calling std::inserter(c)
, where c
is the target container. The first example here shows an inserter into an std::multiset
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.