简体   繁体   English

在 C++ 中合并排序的 Arrays 出现问题

[英]Trouble with Merging Sorted Arrays in C++

I am struggling to solve this problem, merging two sorted arrays (or vectors in this specific case).我正在努力解决这个问题,合并两个排序的 arrays (或在这种特定情况下的向量)。 I am getting very weird output when logging the vector elements to the console.将矢量元素记录到控制台时,我变得非常奇怪 output 。 My ideal output would be all of the numbers in order.我理想的 output 将是所有的数字。

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:假设您有理由不使用std::merge ,则可以手动完成,前提是:

  • 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
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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