I think your problem is that these lines:
if (que1.empty()){
for (int m = j; m < counterq2; m++){
que_merge.push_back(que2.at(m));
}
} else {
for (int l = i; l < counterq1; ++l) {
que_merge.push_back(que1.at(l));
}
}
doesn’t do what you expect.
As far as I can see, your idea is to merge the remaining element from either que1
or que2
.
However, that is not what you get from this code as the elements in que1
and que2
is never erased. In other words – the check for an empty queue is rather meaningless and you can’t be sure that all elements are added to que_merge
So when you do:
for (int l = 0; l < (counterq1+counterq2); l++) {
cout << que_merge.at(l) << endl;
}
you may read beyond the number of elements in que_merge
Tip:
Don’t count the number of elements your self. Use size()
(like que_merge.size()
) instead. For instance:
for (int l = 0; l < que_merge.size(); l++) {
cout << que_merge.at(l) << endl;
}
or a range based loop like:
for (const auto& s : que_merge) {
cout << s << endl;
}
2
solved Vectors And Merging