Trouble with Merging Sorted Arrays in C++

  array-merge, arrays, c++, merge, sorting

I am struggling to solve this problem, merging two sorted arrays (or vectors in this specific case). I am getting very weird output when logging the vector elements to the console. My ideal output would be all of the numbers in order.

Here is the code:

#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> vec1 = {0, 3, 4, 31};
  vector<int> vec2 = {4, 6, 30};

  vector<int>::iterator it1 = vec1.begin();
  auto it2 = vec2.begin();

  bool keep_going = true;

  for ( ; it2 != vec2.end(); it2++) {
    for ( ; it1 != vec1.end() && keep_going; it1++) {
      if (*it1 < *it2) {
        vec1.insert(it1, *it2);
        keep_going = false;
      }
    }
    keep_going = true;
  }

  for (int i = 0; i < vec1.size(); i++) {
    cout << vec1[i] << endl;
  }

  return 0;
}

Here is what the console says:

49
0
4
0
3
4
31
free(): invalid pointer
exited, aborted

Source: Windows Questions C++

LEAVE A COMMENT