Consider the following.
I have two std::set
s 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.
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.