orinj
orinj

Reputation: 1

Trouble with Merging Sorted Arrays in C++

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

Upvotes: 0

Views: 79

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148880

Assuming that you have a reason for not using std::merge, it can be done by hand provided:

  • you do not used nested loops
  • you reset iterators after each insert (the insert invalides the operator)

The merge operation could be coded as:

  while(it2 != vec2.end()) {                             // loop while smth to insert
    while((it1 != vec1.end()) && (*it1 <= *it2)) it1++;  // search in vec1 where to insert
    int i = it1 - vec1.begin();                          // store the position
    vec1.insert(it1, *it2++);                            // insert the value
    it1 = vec1.begin() + i + 1;                          // and restore the iterator
  }

Upvotes: 1

Related Questions