Std :: merge merge two std :: vector coredump

The following code ends with a core dump. What am I doing wrong?

std::vector<int> a;
a.push_back(1);
a.push_back(4);
a.push_back(7);
std::vector<int> b;
b.push_back(2);
b.push_back(5);
b.push_back(8);
std::vector<int> c;
c.clear();


std::merge(a.begin(), a.end(), b.begin(), b.end(), c.begin());
for (it=c.begin(); it!=c.end(); ++it)
    std::cout << *it << endl;

Is there any other merge function in stl or boost that I could use?

Thank!

+5
source share
4 answers

The problem is that yours is cempty, because it was initialized without elements, not to mention an unnecessary call clear(). std::merge()takes an output iterator as the last argument. If it c.begin()refers to the beginning std::vector, which already contains enough elements, then this is not a problem - these elements will simply be overwritten. Be that as it may, you invoke undefined behavior by writing values ​​to memory beyond the end of the vector.

c , :

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

std::back_insert_iterator, , push_back(). reserve() . , c , std::merge(). :

#include <iterator>

// ...

c.reserve(a.size() + b.size());
std::merge(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(c));
+9
std::merge(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(c));
                                                   ^^^^^^^^^^^^^^^^^^^^^^^

, c.begin(), *c.begin(), *(c.begin() + 1) .., undefined, . .

  • , c , , . , c.resize(a.size()+b.size()); merge
  • std::back_insert_iterator. . , *it = x, it back_insert_iterator, push_back x .

. back_inserter - , .

+2

c, , , , ( -), back_insert_iterator, push_back :

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

c , . :

#include <iterator>
...
std::merge(a.begin(), a.end(),
           b.begin(), b.end(),
           std::back_inserter(c));
+1

All Articles