简体   繁体   中英

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

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
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM