Mergesort - std::bad_alloc thrown when trying to assign vector
Good afternoon ladies and gents. So, it is not my day for errors. Implementing Mergesort (not in-place) in C++, and I'm having real trouble with the code, with no idea why. The second-to-last line of the mergeSort()
function assigns the result of the merge()
to a vector of ints, result
. This line (the actual allocation, not the function) throws a bad_alloc
error, and I have no idea why.
The internet suggests that bad_alloc
is mostly thrown due to out-of-memory errors, but this cannot be the case as the first time its called is on a vector of 500 ints, which should be nowhere near too much memory (what is that, like 2 Kb on a 32-bit int?). I assume I'm doing something silly and incorrect for C++, but I don't know what. I tried calling what()
on the exception, but that just returns its name. The code:
vector<int> Sorting::mergeSort(vector<int> A) {
// If the length of A is 0 or 1, it is sorted.
if(A.size() < 2) return A;
// Find the mid-point of the list.
int midpoint = A.size() / 2;
// Declare the left/right vectors.
vector<int> left, right;
// Declare the return vector.
vector<int> result (A.size());
for(int i = 0; i < midpoint; ++i) {
left.push_back(A.at(i));
}
for(int i = midpoint; i < A.size(); ++i) {
right.push_back(A.at(i));
}
left = mergeSort(left);
right = mergeSort(right);
result = merge(left, right);
return result;
}
vector<int> merge(vector<int> left, vector<int> right) {
vector<int> result;
while(left.size() > 0 && right.size() > 0) {
if(left.front() <= right.front()) {
result.push_back(left.front());
left.erase(left.begin());
} else {
result.push_back(right.front());
开发者_开发技巧 right.erase(right.begin());
}
}
if(left.size() > 0) {
for(int i = 0; i < left.size(); ++i) {
result.push_back(left.at(i));
}
} else {
for(int i = 0; i < right.size(); ++i) {
result.push_back(right.at(i));
}
}
}
If I re-write the merge
function to just take a reference to result
and edit it during the function, it works fine, but I wanted to keep the code as close as possible to the 'standard' psuedo-code given for merge-sort.
I appreciate any help, thanks.
In the Merge
function, vector<int> result
is not being returned.
精彩评论