Take a look at the loop inside
merge_sorted()
:
for(int i = 0; i < a.size() + b.size(); ++i)
a.push_back(b[i]);
There are two problems here:
The first is that every time the loop test is reached, it recalculates the end condition. Since you are continually calling push_back() on vector a, it's always growing, and the test will always be true. Eventually, the vector will run out of space and the program will crash.
The second thing is the test itself. Even if the value of
a.size() + b.size()
was only calculated once, it's not correct. You only want to push the
b.size()
elements into a, so your test should probably be
i < b.size()
But this is "old school" C++ programming. If you've got a C++11 or later compiler you could use a range-based for loop e.g.
for(auto i : b)
a.push_back(i);
Another way to approach this would be to use
vector::insert()
a.insert(a.end(), b.begin(), b.end())l
Be sure to look at the documentation for vector class here:
std::vector - cppreference.com[
^]