Question

This question might appear to be very stupid but I don't understand how to merge two sorted vectors with std::merge.

I tried some code using cplusplus reference.

struct t
{
  t(int x):a(x){}
  int a;
};
bool operator<(const t& p,const t&b)
{
  return p.a<b.a;
}

 int main()
 {
  vector<t> a,b,c;
  a.push_back(t(10));
  a.push_back(t(20));
  a.push_back(t(30));
  b.push_back(t(1));
  b.push_back(t(50));
  merge(a.begin(),a.end(),b.begin(),b.end(),c.begin());
  return 0;
 }

There is a segmentation fault with this code.

Was it helpful?

Solution

You will want to make sure c is big enough, or grows:

std::merge(a.begin(),a.end(),b.begin(),b.end(),std::back_inserter(c));

Alternatively:

c.resize(a.size() + b.size());
std::merge(a.begin(),a.end(),b.begin(),b.end(),c.begin());

See it Live On Coliru

#include <algorithm>
#include <vector>
#include <iterator>
struct t
{
    t(int x):a(x){}
    int a;
};
bool operator<(const t& p,const t&b)
{
    return p.a<b.a;
}

int main()
{
    std::vector<t> a,b,c;
    a.push_back(t(10));
    a.push_back(t(20));
    a.push_back(t(30));
    b.push_back(t(1));
    b.push_back(t(50));
    std::merge(a.begin(),a.end(),b.begin(),b.end(),std::back_inserter(c));
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top