Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging std::sets into std::vector

Consider the following.

I have two std::sets and want to merge them in the std::vector in sorted order.

Which is the most effective way to do that?

I did something like this, but I think that there must be a better way of doing it.

std::set<int> S1;
std::set<int> S2;
// ....
// Initialization of sets
// ....

std::vector V;

std::set<int>::iterator iter;

for(iter = S1.begin(); iter!=S1.end(); ++iter)
{
    V.push_back(*iter);
}

for(iter = S2.begin(); iter!=S2.end(); ++iter)
{
    V.push_back(*iter);
}

std::sort(V.begin(), V.end());

Here is my code, is there more effective way? Thanks in advance.

like image 628
Eduard Rostomyan Avatar asked Dec 29 '25 23:12

Eduard Rostomyan


1 Answers

std::merge should do the trick, since S1 and S2 are sorted:

// Initialization of sets
// ....
std::vector V;

std::merge(S1.begin(), S1.end(), S2.begin(), S2.end(), std::back_inserter(V));

// instead of V.begin() -- thanks for the correction.

like image 171
gleusch Avatar answered Jan 01 '26 13:01

gleusch