this is my mergesort function, I can not understand why am i getting always a “vector subscript out of range” error in VC++ express 2010.
vector<int> Ordinatore::doMerge(vector<int> &v1, vector<int> &v2) {
int dimV1 = v1.size();
int dimV2 = v2.size();
int dimTotale = dimV1 + dimV2;
vector<int> merged;
int lh, rh;
lh=0;rh=0;
while(lh < dimV1) {
if (rh < dimV2 && v1[lh] <= v2[rh]) {
merged.push_back(v1[lh]);
lh++;
/* the trouble should start here as far as I've seen with cout & debugging */
while (rh < dimV2 && v2[rh] <= v1[lh]) {
merged.push_back(v2[rh]);
rh++;
}
}
else {
while (rh < dimV2 && v2[rh] <= v1[lh]) {
merged.push_back(v2[rh]);
rh++;
}
merged.push_back(v1[lh]);
lh++;
}
}
return merged;
}
The problem is in the top of your loop:
When that
lh++in theelseis executed,lhis incremented and thewhile(lh < dimV1)restarts. Lets assume that it’s made it all the way tolh == dimV1 - 1…ifcondition evaluates totrue,lh++is executed right were you’ve marked “the trouble should start here“.while (rh < dimV2 && v2[rh] <= v1[lh])will cause a crash becauselhnow equalsdimV1but you’re using it to indexv1.You can read more about Merge Sorts in this Wikipedia Article.