[英]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
,则可以手动完成,前提是:
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.